Python2.x Python JSON
This section will introduce how to encode and decode JSON objects using the Python language.
JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write.
To use JSON functions, you need to import the json library: import json.
| Function | Description |
|---|---|
| json.dumps | Encodes a Python object into a JSON string |
| json.loads | Decodes an encoded JSON string into a Python object |
json.dumps
json.dumps is used to encode a Python object into a JSON string.
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-formatted 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 above code outputs:
[{"a": 1, "c": 3, "b": 2, "e": 5, "d": 4}]
Use parameters to format the JSON output:
Example
#!/usr/bin/python
import json
data =[{'a' : 1,'b' : 2,'c' : 3,'d' : 4,'e' : 5}]
data2 = json.dumps({'a': '','b': 7}, sort_keys=True, indent=4, separators=(',',': '))
print(data2)
The above code outputs:
{ "a": "", "b": 7}
Conversion table from Python native 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 data in native Python types.
Syntax
json.loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])
Example
The following example demonstrates how Python decodes a JSON object:
Example
#!/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 outputs:
{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 information, refer to: https://docs.python.org/2/library/json.html.
Using a third-party library: Demjson
Demjson is a third-party Python module that can be used to encode and decode JSON data. It includes formatting and validation features from JSONLint.
Github address: https://github.com/dmeranda/demjson
Official website: http://deron.meranda.us/python/demjson/
Environment Setup
Before using Demjson to encode or decode JSON data, we need to install the Demjson module first. In this tutorial, we will download Demjson and install it:
$ 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
| Function | Description |
|---|---|
| encode | Encodes a Python object into a JSON string |
| decode | Decodes an encoded JSON string into a Python object |
encode
The Python encode() function is used to encode a Python object into a JSON string.
Syntax
demjson.encode(self, obj, nest_level=0)
Example
The following example encodes an array into JSON-formatted 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 above code outputs:
[{"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 data in native Python types.
Syntax
demjson.decode(self, txt)
Example
The following example demonstrates how Python decodes a JSON object:
Example
#!/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 outputs:
{u'a': 1, u'c': 3, u'b': 2, u'e': 5, u'd': 4}
YouTip