新聞中心
JSON函數(shù)

創(chuàng)新互聯(lián)建站是一家專(zhuān)注于成都網(wǎng)站建設(shè)、成都網(wǎng)站設(shè)計(jì)與策劃設(shè)計(jì),沙坪壩網(wǎng)站建設(shè)哪家好?創(chuàng)新互聯(lián)建站做網(wǎng)站,專(zhuān)注于網(wǎng)站建設(shè)十余年,網(wǎng)設(shè)計(jì)領(lǐng)域的專(zhuān)業(yè)建站公司;建站業(yè)務(wù)涵蓋:沙坪壩等地區(qū)。沙坪壩做網(wǎng)站價(jià)格咨詢(xún):13518219792
使用 JSON 函數(shù)需要導(dǎo)入 json 庫(kù):import json。
舉例說(shuō)明,如下:
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ù),返回結(jié)果為字典:{'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串轉(zhuǎn)換為字典:{'age': 20, 'status': True, 'name': 'niuniu'}相關(guān)推薦:《python視頻教程》
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) #將字典轉(zhuǎn)換為json串寫(xiě)入文件寫(xiě)入的a.json如下:
{"age": 18, "name": "niuniu"}
json.dumps()
import json
dic = {'name': 'niuniu', 'age': 18}
print(json.dumps(dic)) #將字典轉(zhuǎn)換為json串:{"name": "niuniu", "age"擴(kuò)展小知識(shí)點(diǎn):
將字典內(nèi)容寫(xiě)入json文件,包含中文。
1. 中文寫(xiě)入json文件后顯示亂碼,怎么解決? ensure_ascii = False
2. 寫(xiě)入的字典內(nèi)容顯示為不一行,顯示不美觀,怎么解決? indent = 4
import json
d = {"Name": "戰(zhàn)神","sex" : ["男","女","人妖"],"Education":{"GradeSchool" : "第一小學(xué)",
"MiddleSchool" : ["第一初中" , "第一高中"], "University" :{ "Name" : "哈佛大學(xué)", "Specialty" : ["一年級(jí)","二年級(jí)"]}}}
with open('a.json', 'w', encoding='utf-8') as f:
# 中文顯示亂碼問(wèn)題, ensure_ascii = False
# json格式化問(wèn)題, indent = 8
# s = json.dumps(d, ensure_ascii=False, indent=8) 字典轉(zhuǎn)換為json 字符串
# f.write(s)
#第二種寫(xiě)法
json.dump(d, f, ensure_ascii=False,indent=8)寫(xiě)入的json文件,a.json:
網(wǎng)站題目:創(chuàng)新互聯(lián)Python教程:Python之JSON函數(shù)介紹
文章URL:http://m.fisionsoft.com.cn/article/cohdppc.html


咨詢(xún)
建站咨詢(xún)
