python-json處理

來源:互聯網
上載者:User

標籤:資訊   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處理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.