Latest web development tutorials

Python JSON

This chapter we will introduce how to use the Python language to encode and decode JSON objects.

Environment Configuration

Before using Python JSON encoding or decoding data, we need to first install JSON module. This tutorial we will download Demjson and installation:

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

JSON Functions

function description
encode Encoding Python object to a JSON string
decode The encoded JSON string is decoded into Python objects


Python encode () function is used to encode Python object to a JSON string.


demjson.encode(self, obj, nest_level=0)


The following examples will be encoded as a JSON array data format:

import demjson

data = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ]

json = demjson.encode(data)
print json

The above code is executed as a result of:



Python can be used demjson.decode () function to decode JSON data. This function returns a Python data type field.


demjson.decode(self, txt)


The following example shows how to decode JSON objects Python:

import demjson

json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

text = demjson.decode(json)
print  text

The above code is executed as a result of:

{u'a': 1, u'c': 3, u'b': 2, u'e': 5, u'd': 4}