[Python3] JSON parsing

Source: Internet
Author: User

Overview

This section will show you how to use Python to encode and decode JSON objects.

JSON is a shorthand for JavaScript Object notation, a lightweight data interchange format that is easy to read and write, and is one of the most commonly used data interaction formats at the front and back.

Standard library

In Python, a standard JSON library is provided for decoding and encoding parsing of JSON strings.

The usual functions are as follows

    • Json.dumps
      Encodes a Python object into a JSON string, returning the JSON strings

    • Json.loads
      Decodes the encoded JSON string into a Python object and returns the data type of the Python

Let's look at the conversion tables for Python objects and JSON types:

python type Json
Dictionary Dict Object
List lists, tuple tuples Array
STR string String
int, long, float Number
True True
False False
None Null
Dictionaries and JSON mutual transfer examples

JSON string-to-dict (dictionary) example

#-*-coding:utf-8-*-__author__='Gubei'ImportJSONif __name__=="__main__":    Print("JSON turn dict") Json_str='{"Name": "Blog Park Valley White", "url": "http://www.cnblogs.com/igubai/", "id": "Cnblog Gubai"}'        #Original Type    Print("Original type:", type (JSON_STR))#turn into a Dict object    #will be converted into a dictionary typeJson_dict =json.loads (JSON_STR)Print("type after conversion:", type (json_dict))#Traverse Dictionary     for(k, V)inchJson_dict.items ():PrintK" : ", V)

Dict dictionary to JSON string example

#-*-coding:utf-8-*-__author__='Gubei'ImportJSONif __name__=="__main__":        Print("dictionary to JSON string") Json_dict= {                "name":"Blog Park Gubei",                "URL":"www.testingunion.com",                "ID":"deeptest"    }                Print("Original type:", type (json_dict))#Convert a dictionary to a JSON string    #will be converted to a string typeJson_str =json.dumps (json_dict)Print("type after conversion:", type (JSON_STR))Print(JSON_STR)

Advanced instances

Let's look at a complex JSON string and how to traverse it after the conversion.

Parse a complex JSON and iterate through all the elements and print them out:

#-*-coding:utf-8-*-__author__='Gubei'ImportJSONif __name__=="__main__":    Print("JSON string parsing advanced instance") Json_demo="""{"blog": [{"Name": "Blog Park", "UID": "Gubai",                    "desc": "Python3"}, {"Name": "Blog Park" _demo ",  "UID": "Gubai_demo", "desc": "Python3_demo"}], "GitHub":                    [{"url": "Https://github.com/gubai", "name": "GitHub",                    "desc": "Open Source Code"}, {"url": "Https://github.com/gubai_demo", "Name": "Github_demo", "desc": "Python3_demo"}]} /c0>"""    #convert JSON strings to dictionariesJson_dict =json.loads (Json_demo)#Traverse Dictionary     for(k, V)inchJson_dict.items ():#output First level, K for Weixin, web; V for its corresponding list is the data in []        PrintK" : ", V) forDatainchV:#Traverse List            #v for []             for(Data_k, Data_v)inchData.items ():#each data is a dictionary in []                #iterate through a dictionary in a list                Print("    ", Data_k," : ", Data_v)
Summary

The parsing of JSON, in a nutshell, is to translate it into a dictionary and manipulate it in Python.

[Python3] JSON parsing

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.