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. In this tutorial we will download Demjson and install it:

$ tar xvfz demjson-1.6.tar.gz
$ cd demjson-1.6
$ python setup.py install

JSON Function

FunctionDescription
encodeEncode Python objects into JSON strings
decodeDecode encoded JSON strings into Python objects

encode

The 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 the 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.

Syntax

demjson.decode(self, txt)

Examples

The following examples show 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}