Python converts the dictionary to its json string

  • 2020-04-02 13:49:37
  • OfStack

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' }

Indeed, JSON is a string representation of a Python dictionary, but a dictionary as a complex object is not directly converted to define its code strings (can't pass so first need to convert them to a string), Python has a call simplejson library can be easily performed as part of the parse and generate JSON, this package has been included in the Python2.6, call JSON mainly contains four methods: Dump and dumps (producing JSON from Python), load and loads (parsing JSON into Python data types). The only difference between dump and dumps is that dump generates a class file object, dumps generates a string, and load and loads parse the class file object and JSON in 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"}'


Related articles: