Python JSON
In this section we will show you how to encode and decode JSON objects using the Python language.
Environment configuration
Before using Python to encode or decode JSON data, we need to install the JSON module first. 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
Describe
Encode to encode a Python object as a JSON string
Decode decoding encoded JSON strings to Python objects
Encode
The Python encode () function encodes a Python object into a JSON string.
Grammar
Demjson.encode (self, obj, nest_level=0)
Instance
The following example encodes an array into JSON-formatted data:
#!/usr/bin/pythonimport Demjsondata = [{' A ': 1, ' B ': 2, ' C ': 3, ' d ': 4, ' E ': 5}]json = Demjson.encode (data) print Json
The result of the above code execution is:
[{"A": 1, "B": 2, "C": 3, "D": 4, "E": 5}]
Decode
Python can use the Demjson.decode () function to decode JSON data. The function returns the data type of the Python field.
Grammar
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 result of the above code execution is:
{u ' a ': 1, U ' C ': 3, U ' B ': 2, U ' E ': 5, U ' d ': 4}
The above is the "Python tutorial" python json content, more relevant content please follow topic.alibabacloud.com (www.php.cn)!