Converts a dictionary into its JSON string in Python _python

Source: Internet
Author: User

#这是Python中的一个字典

DIC = {' str ': ' is a string ', ' list ': [1, 2, ' A ', ' B '], ' sub_dic ': {' sub_str ': ' The ' is Sub Str ', ' sub_list ': [1, 2, 3]}, ' End ': ' End '} 

This is a JSON object in JavaScript

Json_obj = {' str ': ' is a string ', ' arr ': [1, 2, ' A ', ' B '], ' sub_obj ': {' sub_str ': ' The ' is Sub Str ', ' sub_list ': [1 , 2, 3]}, ' End ': ' End '}

In fact, JSON is the string representation of a Python dictionary, but a dictionary as a complex object cannot be converted directly into a string that defines its code (it cannot be passed so it needs to be converted to a string). Python has a library called Simplejson to facilitate the generation and parsing of JSON, which is already contained in Python2.6, and is called JSON, which consists of four methods: Dump and dumps (generate 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 strings, and similarly load and loads parse the class file object and the string format for JSON

Import json dic = {' str ': ' This is a string ', ' list ': [1, 2, ' A ', ' B '], ' sub_dic ': {' sub_str ': ' The ' is Sub Str ', ' sub_l  Ist ': [1, 2, 3]}, ' End ': ' End '} json.dumps (DIC) #output: # ' {' sub_dic ': {' sub_str ': ' The ' is Sub Str ', ' sub_list ': [1, 2, 3]}, "End": "End", "List": [1, 2, "a", "B"], "str": "It 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.