Python JSON

In this chapter, we will introduce how to use Python language to encode and decode JSON objects.

JSON (JavaScript Object Notation) is a lightweight data interchange format, easy for humans to read and write.


JSON Functions

To use JSON functions, you need to import the json library:import json。

FunctionDescription
json.dumps Encode Python objects into JSON strings
json.loadsDecode encoded JSON strings into Python objects

json.dumps

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

Syntax

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)

Example

The following example encodes an array into JSON format data:

Example

#!/usr/bin/python
import json

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

data2 = json.dumps(data)
print(data2)

The result of the above code execution is:

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

Use parameters to format JSON data output:

Example

#!/usr/bin/python
import json

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

data2 = json.dumps({'a': 'Example', 'b': 7}, sort_keys=True, indent=4, separators=(',', ': '))
print(data2)

The result of the above code execution is:

{
    "a": "Example",
    "b": 7
}

Conversion table from Python primitive types to JSON types:

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

json.loads

json.loads is used to decode JSON data. This function returns the data type of Python fields.

Syntax

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

Example

The following example shows how Python decodes JSON objects:

Example

#!/usr/bin/python
import json

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

text = json.loads(jsonData)
print(text)

The result of the above code execution is:

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

Conversion table from JSON types to Python types:

JSON Python
object dict
array list
string unicode
number (int) int, long
number (real) float
true True
false False
null None

For more content, refer to:https://docs.python.org/2/library/json.html。


Using a Third-party Library: Demjson

Demjson is a third-party module library for Python, which can be used to encode and decode JSON data, and includes JSONLint's formatting and validation features.

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

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

Environment Configuration

Before using Demjson to encode or decode JSON data, we need to install the Demjson module first. In this tutorial, we will downloadDemjsonand install:

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

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

JSON Functions

FunctionDescription
encode Encode Python objects into JSON strings
decodeDecode encoded JSON strings into Python objects

encode

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

Syntax

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

Example

The following example encodes an array into JSON format data:

Example

#!/usr/bin/python
import demjson

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

json = demjson.encode(data)
print(json)

The result of the above code execution is:

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

decode

Python can use the demjson.decode() function to decode JSON data. This function returns the data type of Python fields.

Syntax

demjson.decode(self, txt)

Example

The following example shows how Python decodes JSON objects:

Example

#!/usr/bin/python
import demjson

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

text = demjson.decode(json)
print(text)

The result of the above code execution is:

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