您好,登錄后才能下訂單哦!
什么是Python中的JSON函數(shù)?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
JSON函數(shù)
使用 JSON 函數(shù)需要導入 json 庫:import json。
舉例說明,如下:
a.json內(nèi)容格式:
{"car":{"price":1100,"color":"red"},"mac":{"price":7999,"color":"black"},"abc":{"price":122,"color":"green"}}
json.load()
import json with open('a.json') as fp: shop_dic = json.load(fp) #從a.json文件內(nèi)讀取數(shù)據(jù),返回結果為字典:{'abc': {'price': 122, 'color': 'green'}, 'mac': {'price': 7999, 'color': 'black'}, 'car': {'price': 1100, 'color': 'red'}} print(shop_dic)
json.loads()
s_json = '{"name":"niuniu","age":20,"status":true}' print(json.loads(s_json)) #將json串轉換為字典:{'age': 20, 'status': True, 'name': 'niuniu'}
json.dump()
import json with open('a.json', 'a+') as fp: dic = {'name': 'niuniu', 'age': 18} fp.seek(0) fp.truncate() json.dump(dic, fp) #將字典轉換為json串寫入文件
寫入的a.json如下:
{"age": 18, "name": "niuniu"} json.dumps() import json dic = {'name': 'niuniu', 'age': 18} print(json.dumps(dic)) #將字典轉換為json串:{"name": "niuniu", "age"
擴展小知識點:
將字典內(nèi)容寫入json文件,包含中文。
1. 中文寫入json文件后顯示亂碼,怎么解決? ensure_ascii = False
2. 寫入的字典內(nèi)容顯示為不一行,顯示不美觀,怎么解決? indent = 4
import json d = {"Name": "戰(zhàn)神","sex" : ["男","女","人妖"],"Education":{"GradeSchool" : "第一小學", "MiddleSchool" : ["第一初中" , "第一高中"], "University" :{ "Name" : "哈佛大學", "Specialty" : ["一年級","二年級"]}}} with open('a.json', 'w', encoding='utf-8') as f: # 中文顯示亂碼問題, ensure_ascii = False # json格式化問題, indent = 8 # s = json.dumps(d, ensure_ascii=False, indent=8) 字典轉換為json 字符串 # f.write(s) #第二種寫法 json.dump(d, f, ensure_ascii=False,indent=8)
寫入的json文件,a.json:
看完上述內(nèi)容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業(yè)資訊頻道,感謝您對億速云的支持。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。