The encoding and decoding methods of json data in Python are described in detail.
This document describes how to encode and decode json data in Python. We will share this with you for your reference. The details are as follows:
Python has built-in json data format processing methods since version 2.6.
1. Data Encoding in json format
In python, The json data format is encoded using the json. dumps method.
#! /Usr/bin/env python # coding = utf8import jsonusers = [{'name': 'Tom ', 'age': 22}, {'name': 'anny ', 'age': 18}] # tuples can also be # users = ({'name': 'Tom ', 'age': 22}, {'name ': 'anny ', 'age': 18}) # output [{"age": 22, "name": "tom" },{ "age": 18, "name": "anny"}] print json. dumps (users)
Users can be a tuples or list object. The elements in an object can be numbers, strings, tuples, lists, None, and boolean values.
#! /Usr/bin/env python # coding = utf8import jsonrandom = (5, [1, 2], "tom \" is good ", (1, 2), 1.5, True, none) # output [5, [1, 2], "tom \" is good ", [1, 2], 1.5, true, null] print json. dumps (random)
2. json format data Decoding
In python, The json format data is decoded using the json. loads method. The above example is used:
#! /Usr/bin/env python # coding = utf8import jsonrandom = (5, [1, 2], "tom \" is good ", (1, 2), 1.5, True, none) jsonObj = json. dumps (random) # output [5, [1, 2], u'tom "is good ', [1, 2], 1.5, True, None] print json. loads (jsonObj)
Here we first encode a data json and then decode the encoded data. It is reasonable to say that the decoded data should be the same as the original data, but we find that all the tuples are replaced with List objects. This involves defining the data format for conversion between python and json. See the following two figures:
Definition of conversion from python to json Data Format
Convert json to python data format definition
From the above two figures, we can see that when python is converted to json, list and tuple are converted to array, while when json is converted to python, array is converted to list only.
Note: The content of the above two images is from the official site of python. The json dumps and loads methods can also be used with other parameters.
For more in-depth use, refer to the official manual:
Http://docs.python.org/2/library/json.html? Highlight = json # json