JSON functions
Use JSON functions to import the JSON library: import JSON.
Function description
Json.dumps to encode a Python object as a JSON string
Json.loads decoding encoded JSON strings to Python objects
Json.dumps
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 an array into JSON-formatted data:
#!/usr/bin/pythonimport Jsondata = {' number ': 6, ' name ': ' pythontab '}jsondata = json.dumps (data) Print Jsondata
The result of the above code execution is:
{"Number": 6, "name": "Pythontab"}
Note: You may find that after performing the above conversion, the data has not changed, here is to say: in JSON, double quotation marks are the symbol of the string split, single quotation marks are not standard.
Use parameters to sort and format the output of JSON data:
#!/usr/bin/pythonimport Jsondata = {' number ': 6, ' name ': ' pythontab '}jsondata = json.dumps (data, Sort_keys=true, indent= 4, separators= (', ', ': ')) print Jsondata
Output results
{ "name": "Pythontab", "number": 6}
Python primitive type conversion table to JSON type:
Python |
JSON |
Dict |
Object |
List, tuple |
Array |
STR, Unicode |
String |
int, long, float |
Number |
True |
True |
False |
False |
None |
Null |
Json.loads
The json.loads is 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 a JSON object:
#!/usr/bin/pythonimport jsonjsondata = ' {' number ': 6, ' name ': ' Pythontab '} ' str = json.loads (jsondata) Print str
The result of the above code execution is:
{u ' number ': 6, U ' name ': U ' pythontab '}
JSON type conversion to Python type comparison table:
JSON |
Python |
Object |
Dict |
Array |
List |
String |
Unicode |
Number (int) |
int, long |
Number (real) |
Float |
True |
True |
False |
False |
Null |
None |
Using third-party libraries: Demjson
Demjson is a third-party module library of Python that can be used to encode and decode JSON data, including the Jsonlint formatting and validation functions.
Environment configuration
Before using Demjson encoding or decoding JSON data, we need to install the Demjson module first.
Method 1: Source code Installation
$ TAR-XVZF demjson-2.2.4.tar.gz
$ CD demjson-2.2.4
$ python setup.py Install
Method 2: Use PIP installation directly
Pip Install Demjson
JSON functions
Function description
Encode to encode a Python object as a JSON string
Decode can use the Demjson.decode () function to decode JSON data. The function returns the data type of the Python field.
Encode syntax
Demjson.encode (self, obj, nest_level=0)
Decode syntax
Demjson.decode (self, txt)