1. 程式人生 > >python-json處理

python-json處理

ict dict dumps asc 寫入 phone count 引號 雙引號

1、json 串就是字符串

2、需要提前引入, 即import

3、將list /字典等 轉化為json數據類型:json.dumps()

#json.dumps(d)       #把list\字典轉為json
#json.dumps(d,indent=8) #把list\字典轉為json, indent 縮進
#json.dumps(d,indent=8,ensure_ascii=False) #可以顯示這中文
import json
d={‘car‘:{‘color‘:‘red‘,‘price‘:‘1000‘,‘count‘:30},
‘phone‘: {‘color‘: ‘red‘, ‘price‘: ‘1000‘, ‘count‘: 30},
‘pen‘: {‘color‘: ‘red‘, ‘price‘: ‘1000‘, ‘count‘: 30},
‘flower‘: {‘color‘: ‘red‘, ‘price‘: ‘1000‘, ‘count‘: 30},
‘手機‘: {‘color‘: ‘yel‘, ‘price‘: ‘1000‘, ‘count‘: 30}
}
#res=json.dumps(d) #把list\字典轉為json
#res=json.dumps(d,indent=8) #把list\字典轉為json, indent 縮進
res=json.dumps(d,indent=8,ensure_ascii=False) #可以顯示這中文
print(res)
print(type(res))

4、將json數據類型python 類型(字典或list):json.loads()

json 數據串 必須為雙引號, 不能為單引號,否則程序報錯

f1=open(‘f1‘,‘r‘,encoding=‘utf-8‘)
res=f1.read()
dict_res=json.loads(res)#將json串 轉化為字典 或者 list, 根據json 串的格式
print(dict_res)
print(type(dict_res))

5、json 自動與文件操作:

json.dump(d,f1,ensure_ascii=False,indent=4)         #dump  操作文件,即將信息自動寫入文件,第一個參數為數據, 第二個為文件對象
#例如
#f1=open(‘f1‘,‘w‘,encoding=‘utf-8‘)
# json.dump(d,f1,ensure_ascii=False,indent=4) #dump 操作文件,即將信息自動寫入文件,第一個參數為數據, 第二個為文件對象
# json.load()

json.load(f1)       #直接傳入文件對象,會自動 讀取

#例如
f1=open(‘f1‘,encoding=‘utf-8‘)
print(json.load(f1))
    

6、

7、





python-json處理