python json
json 是一种轻量级的数据交换格式。它基于 ECMAScript 规范的一个子集,采用完全独立于编程语言的文本格式来存储和表示数据。简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。
使用 JSON 函数需要导入 json 库:import json。
函数 | 描述 |
---|---|
json.dumps | 将 Python 对象编码成 JSON 字符串 |
json.loads | 将已编码的 JSON 字符串解码为 Python 对象 |
Python 编码为 JSON 类型转换对应表:
Python | JSON |
---|---|
dict | object |
list, tuple | array |
str | string |
int, float, int- & float-derived Enums | number |
True | true |
False | false |
None | null |
JSON 解码为 Python 类型转换对应表:
JSON | Python |
---|---|
object | dict |
array | list |
string | str |
number (int) | int |
number (real) | float |
true | True |
false | False |
null | None |
实例将python数据结构转化为json json.dumps():
1 import json 2 3 # Python 字典类型转换为 JSON 对象 4 data = { 5 'a' : 1, 6 'b' :'你好', 7 'c' :'hello' 8 } 9 10 json_str = json.dumps(data) 11 print ("Python 原始数据:", repr(data)) 12 print ("JSON 对象:", json_str)
Python 原始数据: {'a': 1, 'c': '祝你快乐', 'b': '你好'}
JSON 对象: {"a": 1, "c": "\u795d\u4f60\u5feb\u4e50", "b": "\u4f60\u597d"}
将json对象转化为python词典 json.loads():
将下面代码加入到上面中
data2 = json.loads(json_str) print ("data2['b']: ", data2['b']) print ("data2['c']: ", data2['c'])
结果:
data2['c']: 祝你快乐
data2['b']: 你好
如果你要处理的是文件而不是字符串,你可以使用 json.dump() 和 json.load() 来编码和解码JSON数据。例如:
1 # 写入 JSON 数据 2 with open('data.json', 'w') as f: 3 json.dump(data, f) 4 5 # 读取数据 6 with open('data.json', 'r') as f: 7 data = json.load(f)