18.Python JSON
Python 语言来编码和解码 JSON 对象
JSON 函数
python中使用JSON函数需要导入json库:import json。
json中的函数有:json.dumps和json.loads
json.dumps将Python对象编码成JSON字符创
json.loads将JSON字符串解码为python对象
以下实例将数组编码为 JSON 格式数据:
import json
data = { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 }
print(json.dumps(data))
结果:
{"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}
使用参数让 JSON 数据格式化输出:
import json
data = {"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}
print(json.dumps(data, sort_keys=True, indent=4, separators=(',', ': ')))
结果:
{
"a": 1,
"b": 2,
"c": 3,
"d": 4,
"e": 5
}
以下实例展示了Python 如何解码 JSON 对象:
import json
data = '{"a":1,"b":2,"c":3,"d":4,"e":5}'
print(json.loads(data))
结果:
{'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 |
除了可以使用内置的 json 模块外,还可以使用第三方库Demjson转换
Demjson 是 python 的第三方模块库,可用于编码和解码 JSON 数据,包含了 JSONLint 的格式化及校验功能。
作者:走路带风的帅界扛把子
本文版权归作者和博客园共有,欢迎转载,但必须给出原文链接,并保留此段声明,否则保留追究法律责任的权利。
浙公网安备 33010602011771号