Python JSON
In this chapter we will introduce how to use Python language to encode and decode JSON objects.
Environment configuration
Before using Python to encode or decode JSON data, we need to install the JSON module first. We will download Demjson and install this tutorial:
$tar xvfz demjson-1.6.tar.gz $cd demjson-1.6 $python setup.py install
JSON function
Function
Description
Encode encodes the Python object into a JSON string
Decode and decoded the coded JSON string to Python to Python Object
encode
Python encode() function is used to encode Python objects into JSON strings.
Syntax
demjson.encode(self, obj, nest_level=0)
Example
The following example encodes an array into JSON format data:
#!/usr/bin/python import demjson data = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ] json = demjson.encode(data) print json
The execution result of the above code is:
[{"a":1,"b":2,"c":3,"d":4,"e":5}]
decode
Python can use the demjson.decode() function to decode JSON data. This function returns the data type of the Python field.
Grammar
demjson.decode(self, txt)
Example
The following example shows how Python decodes JSON objects:
#!/usr/bin/python import demjson json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; text = demjson.decode(json) print text
The execution result of the above code is:
{u'a': 1, u'c': 3, u'b': 2, u'e': 5, u'd': 4}
The above is the content of [python tutorial] Python JSON. For more related content, please pay attention to PHP Chinese Net (www.php.cn)!