Python解析JSON【python自帶json庫】【將 Python物件編碼成 JSON 字串 || 將JSON字串解碼成Python物件】
阿新 • • 發佈:2021-07-08
JSON 庫
使用 JSON 庫需要匯入 json 庫:import json
函式 | 描述 |
---|---|
json.dumps | 將 Python 物件編碼成 JSON 字串 |
json.loads | 將已編碼的 JSON 字串解碼為 Python 物件 |
json.dumps
json.dumps 用於將 Python 物件編碼成 JSON 字串。
語法
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)
例項
以下例項將陣列編碼為 JSON 格式資料:
#!/usr/bin/python import json data = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ] json = json.dumps(data) print json 以上程式碼執行結果為: [{"a": 1, "c": 3, "b": 2, "e": 5, "d": 4}] 使用引數讓 JSON 資料格式化輸出: >>> import json >>> printjson.dumps({'a': 'Runoob', 'b': 7}, sort_keys=True, indent=4, separators=(',', ': ')) { "a": "Runoob", "b": 7 }
python 原始型別向 json 型別的轉化對照表:
Python | JSON |
---|---|
dict | object |
list, tuple | array |
str, unicode | string |
int, long, float | number |
True | true |
False | false |
None | null |
json.loads
json.loads 用於解碼JSON 資料。該函式返回 Python物件的資料型別。
語法
json.loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])
例項
以下例項展示了Python物件如何解碼JSON 物件:
#!/usr/bin/python import json jsonData = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; text = json.loads(jsonData) print text 以上程式碼執行結果為: {u'a': 1, u'c': 3, u'b': 2, u'e': 5, u'd': 4}
json 型別轉換到 python 的型別對照表:
JSON | Python |
---|---|
object | dict |
array | list |
string | unicode |
number (int) | int, long |
number (real) | float |
true | True |
false | False |
null | None |