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 setup.py install
JSON Functions
function | description |
---|---|
encode | Encoding Python object to a JSON string |
decode | The encoded JSON string is decoded into Python objects |
encode
Python encode () function is used to encode Python object to a JSON string.
grammar
demjson.encode(self, obj, nest_level=0)
Examples
The following examples will be encoded as a JSON array data format:
#!/usr/bin/python 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:
[{"a":1,"b":2,"c":3,"d":4,"e":5}]
decode
Python can be used demjson.decode () function to decode JSON data. This function returns a Python data type field.
grammar
demjson.decode(self, txt)
Examples
The following example shows how to decode JSON objects Python:
#!/usr/bin/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}