在python中,字典的输出内容跟json格式内容一样,但是字典的格式是字典,json的格式是字符串,所以在传输的时候(特别是网页)要转换使用。
重要函数
编码:把一个Python对象编码转换成Json字符串 json.dumps()
解码:把Json格式字符串解码转换成Python对象 json.loads()
In [1]: import json
In [2]: dic = { 'str': 'this is a string', 'list': [1, 2, 'a', 'b'], 'sub_dic': { 'sub_str': 'this is sub str', 'sub_list': [1, 2, 3] }, 'end': 'end' }
In [3]: type(dic)
Out[3]: dict
In [5]: json_obj=json.dump(dic)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-5-1959d613a6c1> in <module>()
----> 1 json_obj=json.dump(dic)
TypeError: dump() takes at least 2 arguments (1 given)
In [6]: json_obj=json.dumps(dic)
In [8]: type(json_obj)
Out[8]: str
In [9]: print json_obj
{"sub_dic": {"sub_str": "this is sub str", "sub_list": [1, 2, 3]}, "end": "end", "list": [1, 2, "a", "b"], "str": "this is a string"}
In [10]: dic1=json.loads(json_obj)
In [11]: type(dic1)
Out[11]: dict
In [12]: print dic1
{u'end': u'end', u'list': [1, 2, u'a', u'b'], u'sub_dic': {u'sub_str': u'this is sub str', u'sub_list': [1, 2, 3]}, u'str': u'this is a string'}
In [13]: print dic
{'sub_dic': {'sub_str': 'this is sub str', 'sub_list': [1, 2, 3]}, 'end': 'end', 'list': [1, 2, 'a', 'b'], 'str': 'this is a string'}
参考:https://docs.python.org/dev/library/json.html
转载于:https://blog.51cto.com/qujunorz/1775294