JSON(JavaScript Object Notation, JS 對(duì)象簡(jiǎn)譜) 是一種輕量級(jí)的數(shù)據(jù)交換格式。它基于 ECMAScript (歐洲計(jì)算機(jī)協(xié)會(huì)制定的js規(guī)范)的一個(gè)子集,采用完全獨(dú)立于編程語(yǔ)言的文本格式來(lái)存儲(chǔ)和表示數(shù)據(jù)。簡(jiǎn)潔和清晰的層次結(jié)構(gòu)使得 JSON 成為理想的數(shù)據(jù)交換語(yǔ)言。 易于人閱讀和編寫,同時(shí)也易于機(jī)器解析和生成,并有效地提升網(wǎng)絡(luò)傳輸效率。
下面通過本文給大家介紹python中的json,一起看看吧
JSON
JSON(Java Script Object Notation)
使用json必須導(dǎo)入json庫(kù):import json
dumps() json的格式化轉(zhuǎn)化 字典轉(zhuǎn)換為字符串
>>> import json>>> data = {'a':1,'b':2,'c':3}>>> json.dumps(data)'{"a": 1, "b": 2, "c": 3}'indent為指定縮進(jìn)數(shù)
>>>json.dumps(data,indent=4) //4為所及的數(shù)
separators()函數(shù)為元素分隔符,對(duì)象鍵值分隔符(目的讓json文件變得更加緊湊)
>>>json.dumps(data,separators(',',':')){"a":1,"b":[1,2,3],"c":3}ensure_ascii()當(dāng)字典中有漢字是時(shí)(ehsure_ascii = False)解決亂碼問題(json默認(rèn)為ascii碼)。
>>>s = json.dumps(data,nsure_ascii=False)
dump() json寫入文件中
>>> with open(r'C:/Users/test.json','w') as f:... json.dump(data,f)...>>>with open(r'C:/Users/test.json','r') as f:... f.read()...'{"a": 1, "b": 2, "c": 3}'loads() 將json文件轉(zhuǎn)化為字典
>>> s = json.dumps(data)>>> s'{"a": 1, "b": 2, "c": 3}'>>> json.loads(s){'a': 1, 'b': 2, 'c': 3}>>>load() 從文件中讀取json數(shù)據(jù)
>>> with open(r'C:/Users/gallo/Desktop/python/小游戲/practice/test.json','r') as f:... json.load(f)...{'a': 1, 'b': 2, 'c': 3}>>>總結(jié)
以上所述是小編給大家介紹的python中的json總結(jié),希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)VEVB武林網(wǎng)網(wǎng)站的支持!
新聞熱點(diǎn)
疑難解答
圖片精選