This section describes how to use Python to encode and decode JSON objects.
Python JSON
This section describes how to use Python to encode and decode JSON objects.
Environment configuration
Before using Python to encode or decode JSON data, we need to install the JSON module. In this tutorial, we will download Demjson and install:
$tar xvfz demjson-1.6.tar.gz$cd demjson-1.6$python setup.py install
JSON Functions
Function
Description
Encode encodes a Python object into a JSON string
Decode decodes the encoded JSON string into a Python object
Encode
The Python encode () function is used to encode a Python object into a JSON string.
Syntax
demjson.encode(self, obj, nest_level=0)
Instance
The following example encodes arrays into JSON data:
#!/usr/bin/pythonimport demjsondata = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ]json = demjson.encode(data)print json
The code execution result 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.
Syntax
demjson.decode(self, txt)
Instance
The following example shows how Python decodes a JSON object:
#!/usr/bin/pythonimport demjsonjson = '{"a":1,"b":2,"c":3,"d":4,"e":5}';text = demjson.decode(json)print text
The code execution result is:
{u'a': 1, u'c': 3, u'b': 2, u'e': 5, u'd': 4}
The above is the python JSON content of the [Python Tutorial]. For more information, see The PHP Chinese website (www.php1.cn )!