JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,易于人阅读和编写。使用 JSON 函数需要导入 json 库:import json。
Python 编码为 JSON 类型转换对应表:
Python | JSON |
---|---|
dict | object |
list, tuple | array |
str | string |
int, float, int- & float-derived Enums | number |
True | true |
False | false |
None | null |
Python中Json的常用方法
方法 | 描述 |
json.dumps() | 将 Python 对象编码成 JSON 字符串 |
json.loads() | 将已编码的 JSON 字符串解码为 Python 对象 |
json.dump() | 将Python内置类型序列化为json对象后写入文件 |
json.load() | 读取文件中json形式的字符串元素转化为Python类型 |
json.dumps()
import json
d = {
'code': 0,
'msg': "操作成功",
'token': "dshkjhakjsh"
}
re = json.dumps(d) # 字典转json
print(re)
print(type(re))
# 格式化显示 json
ret = json.dumps(d, ensure_ascii=False, indent=4)
print(ret)
输出:
可以看到,原先的字典中单引号转换为 json 后已经变成双引号了,最后一个print也按照指定的缩进进行了对应的展示。
{"code": 0, "msg": "\u64cd\u4f5c\u6210\u529f", "token": "dshkjhakjsh"}
<class 'str'>
{
"code": 0,
"msg": "操作成功",
"token": "dshkjhakjsh"
}
json.loads()
import json
s = '''
{
"code":0,
"msg":"操作成功",
"token":"dshkjhakjsh"
}
'''
ret = json.loads(s) # json转字典
print(ret)
print(type(ret))
输出:
{'code': 0, 'msg': '操作成功', 'token': 'dshkjhakjsh'}
<class 'dict'>
json.dump()
import json
data = {
'name': 'xiaoh',
'a': [1, 2, 3, 4],
'b': (1, 2, 3)
}
with open('json_test.txt', 'w+') as f:
json.dump(data, f)
运行结果如下,将python字典转为json并写入文件中。
json.load()
import json
with open('json_test.txt', 'r') as f: # 将上个实例中生成的文件内容转为字典
data = json.load(f)
print(data)
print(type(data))
输出:
{'name': 'xiaoh', 'a': [1, 2, 3, 4], 'b': [1, 2, 3]}
<class 'dict'>