JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,易于人阅读和编写。
使用 JSON 函数需要导入 json 库:import json。
| 函数 | 描述 |
|---|---|
| json.dumps | 将 Python 对象编码成 JSON 字符串 |
| json.loads | 将已编码的 JSON 字符串解码为 Python 对象 |
import json
data = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ]
json.dumps(data)
'[{"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}]'
import json
jsonData = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
json.loads(jsonData)
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
python 原始类型向 json 类型的转化对照表:
| Python | JSON |
|---|---|
| dict | object |
| list, tuple | array |
| str, unicode | string |
| int, long, float | number |
| True | true |
| False | false |
| None | null |
json 类型转换到 python 的类型对照表:
| JSON | Python |
|---|---|
| object | dict |
| array | list |
| string | unicode |
| number (int) | int, long |
| number (real) | float |
| true | True |
| false | False |
| null | None |