標籤:資訊 phone flow 字元 load 資料 寫入 單引號 dump
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處理