編碼:json.dumps() 把python對象編碼轉換成json字符串python
解碼:json.loads()把json格式字符串解碼轉換成python對象json
- #!/usr/bin/python3
- from json import *
- if __name__=="__main__":
- d={}
- d['a'] =1
- d['b']=2
- d[3]='c'
- d[4]=['k','k1']
- #將Python dict類型轉換成標準Json字符串
- k=JSONEncoder().encode(d)
- print(type(k))
- print(k)
- <type 'str'>
-
{"a": 1, "3": "c", "b": 2, "4": ["k", "k1"]}編碼
##################################################spa
- #將json字符串轉換成Python dict類型
- json_str='{"a":1,"b":2,"3":"c","4":["k","k1"]}'
- d=JSONDecoder().decode(json_str)
- print(type(d))
- print(d)
<type 'str'>
<type 'dict'>
{u'a': 1, u'3': u'c', u'b': 2, u'4': [u'k', u'k1']}code