Example of Python Json serialization and deserialization, json serialization

Source: Internet
Author: User

Example of Python Json serialization and deserialization, json serialization

Different programming languages have different data types, such:

Python data types include dict, list, string, int, float, long, bool, and None)
Java data types include bool, char, byte, short, int, long, float, and double)
C Data types include bit, bool, char, int, short, long, unsigned, double, and float)
Tcl data types (int, bool, float, string)
Ruby data types (Number, String, Ranges, Symbols, true, false, Array, and Hash)
...

They all have string types!

To realize object transfer between different programming languages, you must serialize the object to a standard format, such as XML, but a better way is to serialize the object to JSON, JSON is a string that can be read by all languages, stored on disks or transmitted over the network.
JSON is not only a standard format, but also faster than XML, and can be read directly on the Web page, which is very convenient.

JSON type Python type
{} Dict
[] List
"String" str
1234.56 int or float
True
False False
Null None

In python, serialization can be understood as converting python object encoding to a json string. deserialization can be understood as decoding a json string into a python data object. In the standard python library, the json Library and the pickle library are provided to process this part.

Json dumps and loads methods can be used to serialize and deserialize data. Specifically, the dumps method can convert the data sequence in json format to the relevant data type in Python; the loads method is the opposite. It is required to convert the python data type to the corresponding data type in json format. During serialization, Chinese characters are always converted to unicode codes. Add the parameter ensure_ascii = False to the dumps function.

The serialization and deserialization of json are as follows:

1. Json serialization:

Import jsonprint (json. _ all _) # view all methods of the json Library ['dump', 'dumps', 'load', 'loads ', 'jsondecoder', 'jsonencoder']

The parameter ensure_ascii = False is not added to the dumps function. The result is as follows:

# Coding: utf-8import jsondict = {'name': 'hangsan ', 'age': 33, 'address': 'hongxinglu'} print ('data type before serialization is: ', type (dict) print ('data before serialization:', dict) # process dict serialization dict_xu = json. dumps (dict) # directly serialize print ('serialized data type: ', type (dict_xu) print ('serialized data:', dict_xu)

The data type before serialization is: <class 'dict '>
Data before serialization: {'name': 'hangsan ', 'address': 'hongxinglu', 'age': 33}
The serialized data type is: <class 'str'>
Serialized data: {"name": "zhangsan", "address": "\ u7ea2 \ u661f \ u8def", "age": 33}

Add the parameter ensure_ascii = False to the dumps function. The result is as follows:

# Coding: utf-8import jsondict = {'name': 'hangsan ', 'age': 33, 'address': 'hongxinglu'} print ('data type before serialization is: ', type (dict) print ('data before serialization:', dict) # process dict serialization dict_xu = json. dumps (dict, ensure_ascii = False) # Add ensure_ascii = False to serialize print ('serialized data type: ', type (dict_xu )) print ('serialized data: ', dict_xu)

The data type before serialization is: <class 'dict '>
Data before serialization: {'address': 'hongxinglu', 'age': 33, 'name': 'hangsan '}
The serialized data type is: <class 'str'>
Serialized data: {"address": "hongxinglu", "age": 33, "name": "zhangsan "}

2. Json deserialization is as follows:

# Coding: utf-8import jsondict = {'name': 'hangsan ', 'age': 33, 'address': 'hongxinglu'} print ('data type before serialization is: ', type (dict) print ('data before serialization:', dict) # process dict serialization dict_xu = json. dumps (dict, ensure_ascii = False) # Add ensure_ascii = False to serialize print ('serialized data type: ', type (dict_xu )) print ('serialized data: ', dict_xu) # deserialize dict_xu to process dict_fan = json. loads (dict_xu) print ('data type after deserialization: ', type (dict_fan) print ('data after deserialization:', dict_fan)

The data type before serialization is: <class 'dict '>
Data before serialization: {'name': 'hangsan ', 'age': 33, 'address': 'hongxinglu '}
The serialized data type is: <class 'str'>
Serialized data: {"name": "zhangsan", "age": 33, "address": "hongxinglu "}
The deserialization data type is: <class 'dict '>
The deserialized data is: {'name': 'hangsan ', 'age': 33, 'address': 'hongxinglu '}

In actual work, serialization or deserialization may be in the form of a file. It cannot be as simple as the one written above. Then we can implement this part, serialize and deserialize the file content. First, let's look at the serialized code. Two steps: 1. serialize the list object first; 2. Write the serialized string to the file:

# Coding: utf-8import jsonlist = ['apple', 'huawei ', 'selenium', 'java', 'python'] # serialize the list first, writing to a file # Two-step operation 1-step serialization of List objects 2-step writing serialized strings into the file json. dump (list, open ('e:/test.txt ', 'w') r1 = open ('e:/test.txt', 'R') print (r1.read ())

["Apple", "Huawei", "selenium", "java", "python"]

Deserialization: 1. Read the string object of the file first; 2. deserialize the object to a list object:

# Coding: utf-8import jsonlist = ['apple', 'huawei ', 'selenium', 'java', 'python'] # serialize the list first, writing to a file # Two-step operation 1-step serialization of List objects 2-step writing serialized strings into the file json. dump (list, open ('e:/test.txt ', 'w') r1 = open ('e:/test.txt', 'R') print (r1.read ()) # ---------------------------------------------------------- # Two-step operation: 1. Read the string object of the file first; 2. deserialize it into list object res = json. load (open ('e:/test.txt ', 'R') print (res) print ('data type:', type (res ))

["Apple", "Huawei", "selenium", "java", "python"]
['Apple', 'huawei ', 'selenium', 'java', 'python']
Data Type: <class 'LIST'>

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

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.