Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Use JSON in Python


May 08, 2021 JSON


Table of contents


Use JSON in Python

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.

Environment

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

JSON function

Function The library
encode Encode the Python object as a JSON string.
decode Decode the JSON encoded string as a Python object.

Code JSON (encode) with Python

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}]

Decode JSON (decode) with Python

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}