【Python】基础学习&技能提升&代码样例3:JSON文本处理

对json的处理,无非是编码和解码两部分

  • 编码:将python数据结构转换为json字符串
  • 解码: 将json字符串转换为python数据结构

另外,还有.json文件的读写

一、编码

json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)

默认转换规则:

Python JSON
dict object -- 对象
list, tuple array
str string
int, float, int 和 float 派生的枚举 数字
True true
False false
None null
python 复制代码
import json

# 编码:将python对象,转为json对象字符串形式
a = {
  'fname' : 'Foo',
  'lname' : 'Bar',
  'email' : None,
  'children' : [
     'Moo',
     'Koo',
     'Roo'
  ]
}
print(a)

json_str = json.dumps(a)
print(json_str)

with open('data.json', 'w') as fh:
    fh.write(json_str)

# dump 和dumps几乎一样,只不过只支持流式输出到文件或者其他stream
with open('data.json', 'w') as fh:
    json.dump(a, fh)

注意,中文直接dumps会变成unicode编码,要解决这个问题需要把参数ensure_ascii=False

python 复制代码
  print(json.dumps({"a":"新的方式"}))
  print(json.dumps({"a": "新的方式"}, ensure_ascii=False))
shell 复制代码
{"a": "\u65b0\u7684\u65b9\u5f0f"}
{"a": "新的方式"}

二、解码

json.loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)

JSON Python
object dict
array list
string str
number (int) int
number (real) float
true True
false False
null None
python 复制代码
# Python 字典类型转换为 JSON 对象
data1 = {
    'no' : 1,
    'name' : 'Runoob',
    'url' : 'http://www.runoob.com'
}
 
json_str = json.dumps(data1)
print ("Python 原始数据:", repr(data1))
print ("JSON 对象:", json_str)
 
# 将 JSON 对象转换为 Python 字典
data2 = json.loads(json_str)
print ("data2['name']: ", data2['name'])
print ("data2['url']: ", data2['url'])

三、 常用操作

常用操作通常就json元素的增删查改,原理就是先解码成python基本数据类型,修改好后再编码成json。

也有高效的增删查改库可以使用,比如jsonpath-ng

python 复制代码
# json_str 增加字段age
data2["age"] = 12
json_str = json.dumps(data2) # 新json

四、 json文件读写

重要利用dumpload函数

python 复制代码
py_data= {
    'no' : 1,
    'name' : 'Runoob',
    'url' : 'http://www.runoob.com'
}

# 写入
with open('data.json', 'w') as fh:
	json_str = json.dumps(py_data)
    fh.write(json_str)

with open('data.json', 'w') as fh:
    json.dump(a, fh)

# 读取
with open("./data.json", "r") as f:
    content = json.load(f)
    print(type(content)) # <class 'dict'>
    print(content)

注意,上面的中文会写入文件中,变成unicode编码,如\u5206\u4eab10\u4e2a\u5f88\u5c0f\u4f17。要保证正文写入。可以按照下面方法:

python 复制代码
# 写入
with open('data.json', 'w', encoding="utf-8") as fh:
    json.dump(a, fh, ensure_ascii=False)
# 读取
with open("./data.json", "r", encoding="utf-8") as f:
    content = json.load(f)

注意,写入时ensure_ascii=False encoding="utf-8"是必须的。

读取时 encoding="utf-8"是必须的,否则会报错:UnicodeDecodeError: 'gbk' codec can't decode byte 0xac in position 123: illegal multibyte sequence

参考

json模块
Python3 JSON 数据解析
jsonpath-ng

相关推荐
Predestination王瀞潞10 分钟前
Python __name__ 与 __main__
开发语言·python
萧曵 丶13 分钟前
Python 字符串、列表、元组、字典、集合常用函数
开发语言·前端·python
梦想的初衷~27 分钟前
Plaxis自动化建模与Python应用全解:从环境搭建到高级案例实战
python·自动化·工程设计·工程软件
Q_Q51100828533 分钟前
python+uniapp基于微信小程序的垃圾分类信息系统
spring boot·python·微信小程序·django·flask·uni-app·node.js
HackerTom35 分钟前
vs code jupyter连gpu结点kernel
python·jupyter·gpu·vs code·远程
雍凉明月夜1 小时前
Ⅱ人工智能学习之深度学习(deep-learning)概述
人工智能·深度学习·学习
d111111111d1 小时前
STM32外设学习--USART串口外设--学习笔记。
笔记·stm32·单片机·嵌入式硬件·学习
weixin_468466851 小时前
遗传算法求解TSP旅行商问题python代码实战
python·算法·算法优化·遗传算法·旅行商问题·智能优化·np问题
河铃旅鹿2 小时前
Android开发-java版:BroadcastReceiver广播
android·笔记·学习
Nina_7172 小时前
pytorch核心组件以及流程
人工智能·pytorch·python