Python——json

來源:互聯網
上載者:User

標籤:寫入檔案   print   day   pre   需要   txt   大哥   tin   with   

json是一種資料類型,其實就是一個字串,是以key—value的形式存在。而且是以雙引號的形式存在

比如:info = {"name":"大哥“,“sex”:“男”}

#json 是一個字串,這是長得像字典
#json 裡面只有雙引號。不能有單引號{"niuhangyang":"123456","lifei":"123456"}
#字典裡面的是單引號

處理json需要引入模組:json

import json

將字串或者從檔案中讀取的json轉字典

json.load()   和檔案相關:

json.loads()  和字串相關:

f = open(‘a.txt)

res = f.read()

print(json.loads(res)}

print(json.load(f))

把字典轉換為字串然後寫入檔案

dumps()方法字典轉換為字串,然後寫入檔案

dict1={‘caoyanyan‘:‘room1‘,‘zhangfei‘:‘room2‘}

str1=json.dumps(dict1)
with open(r‘E:\caopeiyang\TestingCode\day4\json練習.txt‘,‘w‘,encoding=‘utf-8‘)as f2:
f2.write(str1)

dump()方法把字典轉換為字串,然後寫入檔案 不需要咱們自己寫入檔案了,人家會幫我們自動寫入

dict1={‘caoyanyan‘:‘room1‘,‘zhangfei‘:‘room2‘}

with open(r‘E:\caopeiyang\TestingCode\day4\json練習.txt‘,‘w‘,encoding=‘utf-8‘)as f2:

json.dump(dict1,f2,indent=4) #json的格式化

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.