Deeply Understand python's summary of json operations, and deeply understand pythonjson

Source: Internet
Author: User

Deeply Understand python's summary of json operations, and deeply understand pythonjson

Json Description: Json, full name JavaScript Object Notation, is a lightweight data exchange format. Json is the most widely used data format for communication between web servers and clients in AJAX. Now it is also commonly used in http requests, so it is natural to learn about json. Python official site: Highlight = json # module-json

Json API usage: Before python version 2.6, You need to download the package and install it before using it. This is a bit similar to SeleniumLibrary in the current RF. But in 2.6, the official document ( clearly states that "there are some important new software packages added to standard libraries, such as multiprocessing and json, but compared with python 3, 2.6 of these packages will not introduce more new features. "Therefore, if you install Python or a later version of shoes, you do not need to download the json package. You can directly import the json package as needed. In the Lib under the installation directory, see the two packages (Click here to read the source code carefully, there will be more gains,) as shown in the following article:

Python and later versions support Json encoding and decoding, and most built-in python types and Json conversion. The simplest example is as follows:

>>> import json>>> data = {"spam" : "foo", "parrot" : 42}>>> in_json = json.dumps(data) # Encode the data>>> in_json'{"parrot": 42, "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. The two commonly used functions are dumps and dump. The only difference between the two functions is that dump converts a python object to a json object to generate a fp file stream, while dumps generates a string:

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

dic1 = {'type':'dic1','username':'loleina','age':16}json_dic1 = json.dumps(dic1)print json_dic1json_dic2 = json.dumps(dic1,sort_keys=True,indent =4,separators=(',', ': '),encoding="gbk",ensure_ascii=True )print json_dic2

The running result is as follows:

If you change the value of the key 'username' In the instance to "test" in Chinese, an error is returned if you do not add the parameter for the first time, but the second parameter can run normally.

In fact, it is a process of understanding the parameters of a function. The following lists several common parameters:

Skipkeys: The default value is False. If the data in the keys of dict is not of the basic python type (str, unicode, int, long, float, bool, None), if it is set to False, A TypeError error is reported. If this parameter is set to True, this type of key is skipped.

Ensure_ascii: The default value is True. If dict contains non-ASCII characters, it will display data similar to \ uXXXX. After it is set to False, it will be displayed normally.

Indent: it should be a non-negative integer. If it is 0 or empty, the data is displayed in one row. Otherwise, the line breaks and the front blank is displayed according to the number of indent, the printed json data is also called pretty-printed json.

Separators: delimiter, which is actually a tuple of (item_separator, dict_separator). The default value is (',', ':'). This indicates that keys in a dictionary are separated by commas, the KEY and value are separated.

Encoding: the default is UTF-8, which sets the encoding method for json data.

Sort_keys: sorts data according to the value of keys.

The Decode process is a process of converting a json object into a python object. Two common functions are loads and load functions. The difference is the same as that between dump and dumps.

If _ name _ = '_ main _': # convert the python object test to the json object test = [{"username": "test", "age ": 16}, (2, 3), 1] print type (test) python_to_json = json. dumps (test, ensure_ascii = False) print python_to_json print type (python_to_json) # convert a json object to a python object json_to_python = json. loads (python_to_json) print json_to_python print type (json_to_python)

The running result is as follows:

From the test results of the above two examples, we can see that after some basic types of python use encode, The tuple type is converted to the list type, and then it is converted back to the python object, the list type is not converted back to the tuple type, and the encoding format has also changed to Unicode encoding. The type change rules are as follows:

Python --> Json

Json --> Python

Json Processing Chinese problems:

I think I can write two articles about how to deal with python strings (in fact I still don't fully understand it ), here we will summarize the problem of using python2.7.11 to process json data. In the early stage of interface testing, the most common thing to deal with is to assemble data into packets of various protocols and then send them out. Then parse the returned message, and then send the data encapsulated in json to the web server embedded in the http body. After the server completes processing, it returns the json data result. Here we need to consider how to assemble and parse the Chinese data in json. The following is a summary of basic learning:

First, the default encoding format for Python 2.7.11 is ascii, while python3 is unicode. When learning codec, garbled characters may occur, unicode is also displayed for Chinese characters in the list, dictionary, or tuple type. When garbled characters occur, you should first look at the current character encoding format, and then look at the current file encoding format, or if the file format is not set, check the default encoding format of IDE. The most admired method is of course to specify the file encoding format for each encoding, such as setting # coding = UTF-8 before the file.

Second, the character string is unicode encoded in Python. Therefore, during encoding and conversion, unicode is usually used as the intermediate encoding, that is, decode other encoded strings first) to unicode, and then from unicode encoding (encode) to another encoding. The function of decode is to convert other encoded strings to unicode encoding, such as str1.decode ('gb2312'), which means to convert the string str1 encoded in gb2312 to unicode encoding. Encode is used to convert unicode to other encoded strings, for example, str2.encode ('gb2312'), which means to convert the unicode encoded string str2 to gb2312 encoding. Therefore, during transcoding, you must first understand the encoding of the str string, decode into unicode, and then encode into other encodings.

Third, after converting json data into python data, a dict type variable is generally obtained. At this time, the internal data is unicode encoded, so it is very painful to display Chinese characters, however, after dict obtains the value of each key, the Chinese text will be displayed normally, as shown below:

# Coding = utf-8import jsonimport sysif _ name _ = '_ main _': # convert the python object test to json object test = {"username": "test ", "age": 16} print type (test) python_to_json = json. dumps (test, ensure_ascii = False) print python_to_json print type (python_to_json) # convert a json object to a python object json_to_python = json. loads (python_to_json) print type (json_to_python) print json_to_python ['username']

Running result:

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

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.