Python's summary of JSON operations

Source: Internet
Author: User

JSON introduction: JSON, full name JavaScript Object Notation, is a lightweight data interchange format. The most extensive application of JSON is the data format for the communication of Web servers and clients in Ajax. It is also often used in HTTP requests, so it is natural to learn a variety of JSON. Python's website: Https://

Json API use: Python before version 2.6, it is necessary to download the package before it can be used, a bit similar to the current RF within the use of seleniumlibrary. But in 2.6, the official document (Https:// clearly stated, "There are some important new packages added to the standard libraries, such as multiprocessing and JSON, But with Python 3, 2.6 of these packages will not introduce more new features. "So install python2.6 above version of the children's shoes, you can not need to download the JSON package, directly in the required place on the import JSON can be used, in the installation directory under the LIB, see the two packages (point into the carefully read these sources, there will be more harvest,) as follows:


The Python2.6 version supports JSON encoding and decoding, supporting most of Python's built-in types and JSON conversions. The simplest example is as follows:

>>>ImportJSON>>> data = {"spam":"Foo","Parrot": 42}>>> In_json = json.dumps (data)#Encode the Data>>>In_json'{"Parrot": "Spam": "foo"}'>>> json.loads (In_json)#Decode into a Python object{"spam":"Foo","Parrot": 42}

The encode process is a process of converting a Python object into a JSON object, and the two commonly used functions are the dumps and dump functions. The only difference between the two functions is that dump converts the Python object into a JSON object to generate an FP file stream, and dumps generates a string:

 Image Image

The use of other parameters is the same. Here are some of the code snippets for learning:

Dic1 = {'type':'Dic1','username':'Loleina',' Age': 16}json_dic1=json.dumps (DIC1)PrintJson_dic1json_dic2= Json.dumps (Dic1,sort_keys=true,indent =4,separators= (',',': '), encoding="GBK", ensure_ascii=True)PrintJson_dic2

The results of the operation are as follows:


If the value of key ' username ' in the instance is replaced with the "test" in Chinese, then the first time without parameter conversion will be an error, but with the second parameter will be able to run normally.


is actually a process of understanding the parameters of a function, here are a few common parameters:

Skipkeys: The default value is False, if the data in the Dict keys is not the basic type of Python (Str,unicode,int,long,float,bool,none), when set to False, They will report TypeError's mistakes. When set to true, this type of key is skipped

ENSURE_ASCII: The default value True, if the dict contains non-ascii characters, it will be similar to the \UXXXX display data, set to False, will be displayed normally

Indent: Should be a non-negative integer, if it is 0, or empty, then one line displays the data, otherwise it will wrap and display the preceding blank in accordance with the number of indent, so that the printed JSON data is also called pretty-printed JSON

Separators: The delimiter, which is actually a tuple (item_separator, Dict_separator), is the default (', ', ': '), which means that there is a "," separation between keys in dictionary, The key and value are separated by ":".

encoding: The default is UTF-8, which sets how JSON data is encoded.

Sort_keys: Sorts the data according to the value of keys.

The decode process is a process of converting a JSON object into a Python object, and the two commonly used functions are the loads and load functions. The difference is the same as dump and dumps.

if __name__=='__main__':    #Convert a Python object test to a JSON objectTest = [{"username":"Test"," Age": 16}, (2,3), 1]    Printtype (test) Python_to_json= Json.dumps (test,ensure_ascii=False)PrintPython_to_jsonPrinttype (Python_to_json)#convert a JSON object into a Python objectJson_to_python =json.loads (Python_to_json)PrintJson_to_pythonPrintType (Json_to_python)

The results of the operation are as follows:


From the test results of the above 2 examples, we can see that after some basic types of Python have passed encode, the tuple type is converted to the list type and then returned to the Python object, the list type is not reversed to a tuple type, and the encoding format has changed. becomes a Unicode encoding. When specific conversions are made, the type change rules are as follows:





JSON handles Chinese issues:

With regard to the processing of Python strings, I think I can write 2 articles (in fact, I'm not quite clear about it) if I go deep into the study, and here we summarize the problem of using python2.7.11 to process JSON data. Prior to doing interface testing, the most processed thing is to assemble the data into a variety of protocol messages, and then send out. Then the returned message is parsed, after the data encapsulated in the JSON embedded in the HTTP inside the body sent to the Web server, and then after the server processing, return JSON data results of the problem. In this case, we need to consider the JSON has Chinese data, how to assemble and how to parse, the following is a summary of basic learning:

First: Python 2.7.11 the default encoding format is ASCII encoding, and Python3 is already Unicode, in the learning codec, there is garbled problem, There is also an issue where the Chinese display in list or dictionary or tuple type is Unicode. When garbled, you should see what the current character encoding format is, and then see what the current file encoding format is, or if the file format is not set, see what the IDE's default encoding format is. The most respected way of course is each encoding, the file encoding format is specified, such as before the file set # coding= Utf-8.

Second: The representation of a string inside Python is Unicode encoding, so in encoding conversion, it is usually necessary to use Unicode as the intermediate encoding, that is, decoding the other encoded string (decode) into Unicode first. From Unicode encoding (encode) to another encoding. The role of Decode is to convert other encoded strings into Unicode encodings, such as Str1.decode (' gb2312 '), to convert gb2312 encoded string str1 into Unicode encoding. The role of encode is to convert Unicode encoding into other encoded strings, such as Str2.encode (' gb2312 '), to convert Unicode encoded string str2 to gb2312 encoding. Therefore, the transcoding must first understand, the string str is what encoding, and then decode into Unicode, and then encode into other encodings

Third: After the JSON data is converted to Python data, generally get a variable of type dict, when the internal data are Unicode encoding, so the Chinese display looks very painful, but for dict to get the value of each key, Chinese will be displayed normally, as follows:

#coding= Utf-8ImportJSONImportSYSif __name__=='__main__':    #Convert a Python object test to a JSON objectTest = {"username":"Test"," Age": 16}    Printtype (test) Python_to_json= Json.dumps (test,ensure_ascii=False)PrintPython_to_jsonPrinttype (Python_to_json)#convert a JSON object into a Python objectJson_to_python =json.loads (Python_to_json)Printtype (Json_to_python)Printjson_to_python['username']

Operation Result:


Python's summary of JSON operations

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: 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.