【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

相关推荐
ヾChen15 分钟前
头歌MySQL——复杂查询
数据库·物联网·学习·mysql·头歌
老虎062718 分钟前
黑马点评学习笔记07(缓存工具封装)
笔记·学习·缓存
Yurko1320 分钟前
【C语言】选择结构和循环结构的进阶
c语言·开发语言·学习
小白学大数据28 分钟前
构建1688店铺商品数据集:Python爬虫数据采集与格式化实践
开发语言·爬虫·python
闲人编程31 分钟前
用Python和Telegram API构建一个消息机器人
网络·python·机器人·api·毕设·telegram·codecapsule
范纹杉想快点毕业38 分钟前
12个月嵌入式进阶计划ZYNQ 系列芯片嵌入式与硬件系统知识学习全计划(基于国内视频资源)
c语言·arm开发·单片机·嵌入式硬件·学习·fpga开发·音视频
大邳草民44 分钟前
深入理解 Python 的“左闭右开”设计哲学
开发语言·笔记·python
im_AMBER1 小时前
React 12
前端·javascript·笔记·学习·react.js·前端框架
暴风鱼划水1 小时前
三维重建【4-A】3D Gaussian Splatting:代码解读
python·深度学习·3d·3dgs
清钟沁桐1 小时前
mlir 编译器学习笔记之四 -- 调度
笔记·学习·mlir