在编写接口传递数据时,往往需要使用JSON对数据进行封装。python和json数据类型的转换,看作为编码与解码。
编码:json.dumps()
| Python | JSON |
|---|---|
| dict | object |
| list, tuple | array |
| str | string |
| int, float, int- & float-derived Enums | number |
| True | true |
| False | false |
| None | null |
解码:json.loads()
| JSON | Python |
|---|---|
| object | dict |
| array | list |
| string | str |
| number (int) | int |
| number (real) | float |
| true | True |
| false | False |
| null | None |
普通的字典类型:
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 4 import json 5 6 d = dict(name='Bob', age=20, score=88) 7 print '编码前:' 8 print type(d) 9 print d

编码后的JSON类型:
1 # python编码为json类型,json.dumps() 2 en_json = json.dumps(d) 3 print '编码后:' 4 print type(en_json) 5 print en_json

解码后的Python类型:
1 # json解码为python类型,json.loads() 2 de_json = json.loads(en_json) 3 print '解码后:' 4 print type(de_json) 5 print de_json

解析后Python类型:
1 # eval()解析json 2 d = dict(name='Bob', age=20, score=88) 3 en_json = json.dumps(d) 4 de_json = eval(en_json) 5 print '解析后:' 6 print type(de_json) 7 print de_json

!!!
浙公网安备 33010602011771号