【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

相关推荐
烛阴1 小时前
武装你的Python“工具箱”:盘点10个你必须熟练掌握的核心方法
前端·python
逆小舟2 小时前
【C/C++】指针
c语言·c++·笔记·学习
杨枝甘露小码2 小时前
Python学习之基础篇
开发语言·python
我是华为OD~HR~栗栗呀2 小时前
23届考研-Java面经(华为OD)
java·c++·python·华为od·华为·面试
武文斌772 小时前
项目学习总结:LVGL图形参数动态变化、开发板的GDB调试、sqlite3移植、MQTT协议、心跳包
linux·开发语言·网络·arm开发·数据库·嵌入式硬件·学习
递归不收敛2 小时前
吴恩达机器学习课程(PyTorch适配)学习笔记:1.3 特征工程与模型优化
pytorch·学习·机器学习
小蕾Java2 小时前
PyCharm 软件使用各种问题 ,解决教程
ide·python·pycharm
Lucky_Turtle2 小时前
【PyCharm】设置注释风格,快速注释
python
kunge1v53 小时前
学习爬虫第四天:多任务爬虫
爬虫·python·学习·beautifulsoup
萧鼎3 小时前
Python schedule 库全解析:从任务调度到自动化执行的完整指南
网络·python·自动化