May 08, 2021 JSON
This tutorial will teach us how to encode and decode JSON using the Python programming language. Let's first prepare the environment for Python programming for JSON.
Before we can encode and decode JSON using Python, we need to install an available JSON module. For this tutorial, download and install Demjson as follows:
$tar xvfz demjson-1.6.tar.gz
$cd demjson-1.6
$python setup.py install
Function | The library |
---|---|
encode | Encode the Python object as a JSON string. |
decode | Decode the JSON encoded string as a Python object. |
Python's encode() function is used to encode Python objects as represented by JSON strings.
Grammar:
demjson.encode(self, obj, nest_level=0)
Example:
The following example shows using Python to convert an array to JSON:
#!/usr/bin/python
import demjson
data = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ]
json = demjson.encode(data)
print json
The execution produces results such as the following:
[{"a":1,"b":2,"c":3,"d":4,"e":5}]
Python can use the demjson.decode() function to handle JSON decoding. This function returns a value decoded from JSON to the appropriate Python type.
Grammar:
demjson.decode(self, txt)
Example:
The following example shows how to decode a JSON object using Python.
#!/usr/bin/python
import demjson
json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
text = demjson.decode(json)
print text
The results are generated on execution as follows:
{u'a': 1, u'c': 3, u'b': 2, u'e': 5, u'd': 4}