Python處理Json資料
阿新 • • 發佈:2018-12-18
JSON是一種輕量級的資料交換格式,易於讀寫,也易於機器的解析。
使用Python處理JSON:
Python自己有json模組,用於將Python物件和json字串進行相互的轉換。
編碼:
使用json.dumps()
將Python隊形編碼轉換成json字串
>>> import json >>> python_obj = [[1,2,3],123,123.123,'abc',{'key1':(1,2,3),'key2':(4,5,6)},True,False,None] >>> json_str=json.dumps(python_obj) >>> print json_str [[1, 2, 3], 123, 123.123, "abc", {"key2": [4, 5, 6], "key1": [1, 2, 3]}, true, false, null]
可以看到在編碼的過程中,Python原始型別會轉化成json型別,轉化表如下
Python | JSON |
---|---|
dict | object |
list, tuple | array |
str, unicode | string |
int, long, float | number |
True | true |
False | false |
None | null |
這個編碼方法還提供了很多引數:
>> python_obj2={"key2": [4, 5, 6], "key1": [1, 2, 3]} >>> json_str2=json.dumps(python_obj2) >>> json_str2=json.dumps(python_obj2,sort_keys=True,indent=2) >>> print json_str2 { "key1": [ 1, 2, 3 ], "key2": [ 4, 5, 6 ] }
這裡sort_keys
是用來對dict物件進行排序的,indent
是用來格式化輸出的。
解碼:
使用json.loads()
將JSON格式字串解碼,轉換成Python物件。
這裡將上面的編碼例子再進行解碼:
>>> print json.loads(json_str)
[[1, 2, 3], 123, 123.123, u'abc', {u'key2': [4, 5, 6], u'key1': [1, 2, 3]}, True, False, None]
這裡會發現string型別的JSON資料轉換成了Unicode型別。
使用引數讓JSON資料格式化輸出:
>>> import json
>>> print json.dumps({'a': 'Runoob', 'b': 7}, sort_keys=True, indent=4, separators=(',', ': '))
{
"a": "Runoob",
"b": 7
}