Python3 JSON 解析
python3 json 解析
json是一种轻量级的数据交互格式,采用完全独立于编程语言的文本格式来存储和表示数据。和xml相比,它更小巧,但描述能力却不差,更适合于在网络上传输数据。
python3 中可以使用 json 模块来对 json 数据进行编解码,它包含了两个函数:
- json.dumps(): 对数据进行编码。
- json.loads(): 对数据进行解码。

在json 的编解码过程中,python 的原始类型与 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 |
json 解码为 python 类型转换对应表:
| json | python |
|---|---|
| object | dict |
| array | list |
| string | str |
| number (int) | int |
| number (real) | float |
| true | true |
| false | false |
| null | none |
json.dumps 与 json.loads 范例
以下范例演示了 python 数据结构转换为json:
范例(python 3.0+)
#!/usr/bin/python3 import json # python 字典类型转换为 json 对象 data = {
'no' : 1,
'name' : 'yapf',
'url' : 'http://www.yapf.com' }
json_str = json.dumps(data) print ("python 原始数据:", repr(data)) print ("json 对象:", json_str)


