1. 程式人生 > >python 中 json 包用法簡單總結

python 中 json 包用法簡單總結

JSON包的引用

在檔案頭部引用json包

import json

python物件與JSON物件的互相轉換

json物件的型別為’str’:

dic = {'b':'I', 'a':123, 'c':'100'}
j1 = json.dumps(dic)
print (j1)
# {"b": "I", "a": 123, "c": "100"}
print (type(j1))
# <class 'str'> 
print (j1[0],j1[1],j1[2])
# { " b

將sort_keys引數置為True時,生成的json物件是按鍵排序的,sort_keys預設為False:

dic = {'b':'I', 'a':123, 'c':'100'}
j2 = json.dumps(dic, sort_keys = True)
print (j2)
# {"a": 123, "b": "I", "c": "100"}

通過indent引數可以設定json物件的縮排格式:

dic = {'b':'I', 'a':123, 'c':'100'}
j3 = json.dumps(dic, sort_keys = True, indent = 4)
print (j3)
# {
#     "a": 123,
#     "b": "I",
#     "c": "100"
# }

通過separators引數可以設定json物件的分隔符:

dic = {'b':'I', 'a':123, 'c':'100'}
j4 = json.dumps(dic, sort_keys = True, separators = ('$','@'))
print (j4)
# {"a"@123$"b"@"I"$"c"@"100"}

列表也可以轉化為json物件:

list1 = [1, 'big', [1, 'a', {'p':'+'}], (['t',2],{'1':'o'}), {'c':0,'d':1}]
j5 = json.dumps(list1)
print (j5)
# [1, "big", [1, "a", {"p": "+"}], [["t", 2], {"1": "o"}], {"c": 0, "d": 1}]

元組轉化為json物件:

tuple1 = (1, 0)
j6 = json.dumps(tuple1)
print (j6)
# [1, 0]

將字典轉換為json字串時,key需為數字或字母,否則報錯,可通過skipkeys引數跳過這些鍵:

dic1 = {1:'one', 2.3:'tPt', 'two':2, (3,4):'thr&four'}
j7 = json.dumps(dic1)
print (j7)
# TypeError: keys must be a string
j8 = json.dumps(dic1, skipkeys = True)
print (j8)
# {"1": "one", "2.3": "tPt", "two": 2}

dumps對中文使用ascii編碼方式,通過將ensure_ascii引數設定為False可輸出中文:

dic_info = {'name':'Elizabeth', 'husband':'達西', 'age':22}
j9 = json.dumps(dic_info)
print (j9)
# {"name": "Elizabeth", "husband": "\u8fbe\u897f", "age": 22}
j10 = json.dumps(dic_info,ensure_ascii=False)
print (j10)
# {"name": "Elizabeth", "husband": "達西", "age": 22}

將json物件解碼為python物件:

dic = {'b':'I', 'a':123, 'c':'100'}
j1 = json.dumps(dic)
decode1 = json.loads(j1)
print (decode1)
# {'b': 'I', 'a': 123, 'c': '100'}

存取JSON檔案

存json檔案,將python物件存到json格式的檔案中不再用dumps,而是要用dump:

dic_info = {'name':'Elizabeth', 'husband':'達西', 'age':22}
filew = open ('Elizabeth.json', 'w', encoding='utf-8')
json.dump(dic_info, filew)
filew.close()

json檔案如下圖所示:
json檔案
讀取json檔案,從json檔案中讀取內容存入python物件,不再用loads而是要用load:

filer = open ('Elizabeth.json', 'r', encoding='utf-8')
Elizabeth = json.load(filer)
filer.close()
print (Elizabeth)
# {'name': 'Elizabeth', 'husband': '達西', 'age': 22}
print (type(Elizabeth))
# <class 'dict'>

python官方幫助文件