Convert a dictionary to its json string in python-Python tutorial

Source: Internet
Author: User
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"}'

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.