python中json的使用


在編寫接口傳遞數據時,往往需要使用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

!!!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM