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

Python JSON


May 10, 2021 Python2


Table of contents


Python JSON

In this section, we'll show you how to encode and decode JSON objects using the Python language.


Environment configuration

Before we can encode or decode JSON data using Python, we need to install the JSON module. For this tutorial we'll download Demjson and install:

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

JSON function

Using the JSON function requires importing the json library: import json.

Function Describe
json.dumps Encode the Python object into a JSON string
json.loads Decode the encoded JSON string as a Python object

json.dumps

json.dumps are used to encode Python objects into JSON strings.

Grammar

json.dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding="utf-8", default=None, sort_keys=False, **kw)

Instance

The following example encodes the array as JSON format data:

#!/usr/bin/python
import json

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

json = json.dumps(data)
print json

The above code execution results are:

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

Use parameters to format the output of the JSON data:

>>> import json
>>> print json.dumps({'a': 'W3Cschool', 'b': 7}, sort_keys=True, indent=4, separators=(',', ': '))
{
    "a": "W3Cschool",
    "b": 7
}

Python original type to json type conversion control table:

Python Json
dict object
list, tuple array
str, unicode string
int, long, float number
True true
False false
None Null

json.loads

json.loads are used to decode JSON data. The function returns the data type of the Python field.

Grammar

json.loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])

Instance

The following example shows how Python decodes JSON objects:

#!/usr/bin/python
import json

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

text = json.loads(jsonData)
print text

The above code execution results are:

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

Type comparison table for json type conversion to Python:

Json Python
object dict
array list
string Unicode
number (int) int, long
number (real) float
true True
false False
Null None

For more information: https://docs.python.org/2/library/json.html.



Use a third-party library: Demjson

Demjson is python's third-party module library that can be used to encode and decode JSON data, including JSONLint's formatting and validation capabilities.

Github Address: https://github.com/dmeranda/demjson

Official address: http://deron.meranda.us/python/demjson/

Environment configuration

Before we can encode or decode JSON data with Demjson, we need to install the Demjson module. For this tutorial we'll download Demjson and install:

$ tar -xvzf demjson-2.2.3.tar.gz
$ cd demjson-2.2.3
$ python setup.py install

For more installation, see: http://deron.meranda.us/python/demjson/install

JSON function

Function Describe
encode Encode the Python object into a JSON string
decode Decode the encoded JSON string as a Python object

encode

The Python encode() function is used to encode Python objects into JSON strings.

Grammar

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

Instance

The following example encodes the array as 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 above code execution results are:

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

decode

Python can decode JSON data using the demjson.decode() function. The function returns the data type of the Python field.

Grammar

demjson.decode(self, txt)

Instance

The following example shows 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 above code execution results are:

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