0%

json in Python

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

Function Description
json.dumps Encode Python objects into JSON strings
json.loads Decode an encoded JSON string into a Python object

json.dumps 🔒

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

1
2
3
4
5
6
7
8
9
10
11
12
13
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)

The following example encodes an array into JSON formatted data:

1
2
3
4
5
6
7
#!/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:

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

Use parameters to format the JSON data output:

1
2
3
4
5
6
>>> import json
>>> print json.dumps({'a': 'DEV', 'b': 7}, sort_keys=True, indent=4, separators=(',', ': '))
{
"a": "DEV",
"b": 7
}

json.loads 🔑

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

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

The following example shows how Python decodes a JSON object:

1
2
3
4
5
6
7
#!/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:

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

💥 Conversion table of python primitive type to json type:

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