The Python dictionary and JSON are very similar in form. In fact, JSON is actually a string representation of the Python dictionary. However, as a complex object, the dictionary cannot be directly converted into a string defining its code, let's analyze it in detail # This is a dictionary in Python
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' }
// This is a JSON object in javascript.
json_obj = { 'str': 'this is a string', 'arr': [1, 2, 'a', 'b'], 'sub_obj': { 'sub_str': 'this is sub str', 'sub_list': [1, 2, 3] }, 'end': 'end' }
In fact, JSON is a string representation of the Python dictionary, but the dictionary, as a complex object, cannot be directly converted into a string defining its code (it cannot be passed, so it must be converted to a string first ), python has a library named simplejson that can easily generate and parse JSON. this package is already included in Python2.6. json mainly contains four methods: dump and dumps (generate JSON from Python), load and loads (parse JSON into Python data type) the only difference between dump and dumps is that dump generates a class file object, dumps will generate a string. Similarly, load and loads will parse the JSON file objects and string format respectively.
import json 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' } json.dumps(dic) #output: #'{"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"}'