两个函数,参考文档:Python 进阶(九):JSON 基本操作 (qq.com)
(136条消息) 【强烈推荐】Python中JSON的基本使用(超详细)_ZSYL的博客-CSDN博客_pythonjson库使用
1.json的基本语法和对应关系
- 名称必须用双引号(即:
" "
)来包括 - 值可以是双引号包括的字符串、数字、true、false、null、JavaScript数组,或子对象
- 数据在name/value中
- 数据见用逗号分隔
- 花括号保存对象
- 方括号保存数组
2. JSON数据类型
Python | JSON |
---|---|
dict | object |
list, tuple | array |
str, unicode | string |
int, long, float | number |
True | true |
False | false |
None | null |
3.常用方法:
方法 描述
json.dumps() 将 Python 对象编码成 JSON 字符串
json.loads() 将已编码的 JSON 字符串解码为 Python 对象
json.dump() 将Python内置类型序列化为json对象后写入文件
json.load() 读取文件中json形式的字符串元素转化为Python类型
json.dump() json.load()
import json
d = {'id':'001', 'name':'张三', 'age':'20'}
with open('test.json', 'w', encoding='utf-8') as f:
json.dump(d, f, indent=4, ensure_ascii=False)
import json
j = '{"id":"001", "name":"张三", "age":"20"}'
d = json.loads(j)
print(d)
json.dumps()
import json
data = {'name':'nanbei','age':18}
# 将Python对象编码成json字符串
print(json.dumps(data))
结果如下:
{"name": "nanbei", "age": 18}
json.loads()
import json
data = {'name':'nanbei','age':18}
# 将Python对象编码成json字符串
# print(json.dumps(data))
# 将json字符串解码成Python对象
a = json.dumps(data)
print(json.loads(a))
结果如下:
{'name': 'nanbei', 'age': 18}