【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

相关推荐
databook9 小时前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室9 小时前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三11 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
用户25191624271114 小时前
Python之语言特点
python
刘立军14 小时前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
数据智能老司机18 小时前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机19 小时前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i20 小时前
django中的FBV 和 CBV
python·django
c8i20 小时前
python中的闭包和装饰器
python
这里有鱼汤1 天前
小白必看:QMT里的miniQMT入门教程
后端·python