方法 | 作用 |
---|---|
json.dumps() | 將python對(duì)象編碼成Json字符串 |
json.loads() | 將Json字符串解碼成python對(duì)象 |
json.dump() | 將python中的對(duì)象轉(zhuǎn)化成json儲(chǔ)存到文件中 |
json.load() | 將文件中的json的格式轉(zhuǎn)化成python對(duì)象提取 |
json.dump()和json.dumps()的區(qū)別
json參數(shù)
json.dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding="utf-8", default=None, sort_keys=False, **kw)
import json x = {'name':'你猜','age':19,'city':'四川'} #用dumps將python編碼成json字符串 y = json.dumps(x) print(y) i = json.dumps(x,separators=(',',':')) print(i) # 輸出結(jié)果 {"name": "\u4f60\u731c", "age": 19, "city": "\u56db\u5ddd"} {"name":"\u4f60\u731c","age":19,"city":"\u56db\u5ddd"}
json.dumps()用于將python對(duì)象轉(zhuǎn)換為json字符串,返回轉(zhuǎn)換后的json字符串
import json #將python對(duì)象轉(zhuǎn)換為json字符串 persons = [ { 'username': "zhaoji", "age": "18", "country": "China" }, { "username": "cyj", "age": "18", "country": "China" } ] #調(diào)用dumps方法轉(zhuǎn)換python對(duì)象 json_str = json.dumps(persons) #打印轉(zhuǎn)換后的json字符串的數(shù)據(jù)類型 print(type(json_str)) #打印轉(zhuǎn)換后的json字符串 print(json_str)
輸出結(jié)果為
class ‘str'>
[{“username”: “zhaoji”, “age”: “18”, “country”: “China”}, {“username”: “cyj”, “age”: “18”, “country”: “China”}]Process finished with exit code 0
json.dump()用于將python對(duì)象轉(zhuǎn)換為字符串并且寫入文件
import json #將python對(duì)象轉(zhuǎn)換為json字符串 persons = [ { 'username': "zhaoji", "age": "18", "country": "China" }, { "username": "cyj", "age": "18", "country": "China" } ] with open("./data/j1.json", "w") as fp: json.dump(persons, fp) fp.close()
寫入文件為
[{“username”: “zhaoji”, “age”: “18”, “country”: “China”}, {“username”: “cyj”, “age”: “18”, “country”: “China”}]
到此這篇關(guān)于Python中json.dumps()函數(shù)的使用解析的文章就介紹到這了,更多相關(guān)Python json.dumps() 內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
標(biāo)簽:鷹潭 黑龍江 惠州 四川 上海 益陽(yáng) 常德 黔西
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Python中json.dumps()函數(shù)的使用解析》,本文關(guān)鍵詞 Python,中,json.dumps,函數(shù),的,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。