First, Python support for JSON
Starting with python2.6, JSON support has been added to the Python standard library, and it is only necessary to manipulate the JSON import json
.
Second, the Python object is converted into a JSON string
When you convert a Python object to a JSON string, you only need the following knowledge:
Conversion rules for 1.python objects to JSON strings:
Python |
JSON |
Dict |
Object |
List, tuple |
Array |
STR, Unicode |
String |
int, long, float |
Number |
True |
True |
False |
False |
None |
Null |
2. Use the following functions mainly:
json.dumps()
The specific parameters of the function (see the link in the appendix for specific usage):
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
Test code:
#构造字典python2json = {}#构造listlistData = [1,2,3]python2json["listData"] = listDatapython2json["strData"] = "test python obj 2 json"#转换成json字符串json_str = json.dumps(python2json)print json_str
Conversion Result:
{ "listData": [ 1, 2, 3 ], "strData": "test python obj 2 json"}
C. JSON string converted to Python object
In the same vein, converting a JSON string into a Python object requires only the following knowledge:
1.json string to Python object conversion rules:
JSON |
Python |
Object |
Dict |
Array |
List |
String |
Unicode |
Number (int) |
int, long |
Number (real) |
Float |
True True |
|
False |
False |
Null |
None |
2. Use the following functions mainly:
json.loads()
The specific parameters of the function (see the link in the appendix for specific usage):
Json.loads (s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]] [] ]]])
Example
Test code:
str = ‘{"listData": [1, 2, 3], "strData": "test python obj 2 json"}‘json2python = json.loads(str)print type(json2python)
Conversion Result:
<type ‘dict‘>
Python objects and JSON convert each other