【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

相关推荐
萧鼎7 小时前
深入解析 Python 的 pytun 库:虚拟网络接口与隧道技术实战指南
服务器·网络·python
西猫雷婶7 小时前
pytorch基本运算-分离计算
人工智能·pytorch·python·深度学习·神经网络·机器学习
数新网络7 小时前
PyTorch
人工智能·pytorch·python
自信的小螺丝钉7 小时前
【大模型手撕】pytorch实现LayerNorm, RMSNorm
人工智能·pytorch·python·归一化·rmsnorm·layernorm
深耕AI7 小时前
PyTorch图像预处理:ToTensor()与Normalize()的本质区别
人工智能·pytorch·python
T1an-17 小时前
Axum web框架【实习】
学习·rust
知识分享小能手7 小时前
React学习教程,从入门到精通, React 新创建组件语法知识点及案例代码(11)
前端·javascript·学习·react.js·架构·前端框架·react
鲸屿1958 小时前
python之socket网络编程
开发语言·网络·python
里昆8 小时前
【AI】Tensorflow在jupyterlab中运行要注意的问题
人工智能·python·tensorflow
AI视觉网奇8 小时前
pycharm 最新版上一次编辑位置
python