In this paper, we describe the encoding and decoding method of JSON format data in Python. Share to everyone for your reference, as follows:
Python has built a processing method for JSON data format starting with version 2.6.
1. JSON Format Data encoding
In Python, the JSON data format encoding uses the Json.dumps method.
#!/usr/bin/env Python#coding=utf8import jsonusers = [{' Name ': ' Tom ', ' Age ': $}, {' name ': ' Anny ', ' age ':] #元组对象也可以 #use rs = ({' name ': ' Tom ', ' Age ': +}, {' name ': ' Anny ', ' age ': +}) #输出 [{"Age": "Name": "Tom"}, {"Age": "" Name ":" Anny "}] Print Json.dumps (users)
Where users can be a tuple object, or it can be a list object. An element within an object can be a number, a string, a tuple, a list, None, and a Boolean value.
#!/usr/bin/env Python#coding=utf8import jsonrandom = (5, [1, 2], "tom\" is Good ", (1, 2), 1.5, True, None) #输出 [5, [1, 2]," Tom\ "is good", [1, 2], 1.5, True, Null]print json.dumps (random)
2. JSON format data decoding
In Python JSON format data decoding using the Json.loads method, the above example is moved:
#!/usr/bin/env Python#coding=utf8import jsonrandom = (5, [1, 2], "tom\" is Good ", (1, 2), 1.5, True, None) jsonobj = JSON.D Umps (Random) #输出 [5, [1, 2], U ' Tom ' is Good ', [1, 2], 1.5, True, None]print json.loads (jsonobj)
This is to encode a data JSON before decoding the encoded data. Logically, the decoded data should be the same as the original data, but we find that the tuple objects are replaced with list objects. This is the definition of the data format that Python and JSON convert to each other. Take a look at the following two graphs:
Python converted to JSON data format definition
JSON converted to Python data format definition
As you can see from the above two graphs, when Python is converted to JSON, the list and the tuple are transformed into an array, and when JSON turns into Python, the array is only turned into a list.
Note: The contents of the above two images are from the official Python site. JSON's dumps and loads methods also have other parameters that can be used.