pmp培訓(xùn)seo網(wǎng)站
簡介
JSON(JavaScript Object Notation) 是一種輕量級的數(shù)據(jù)交換格式,它使得人們很容易的進(jìn)行閱讀和編寫
同時也方便了機(jī)器進(jìn)行解析和生成。適用于進(jìn)行數(shù)據(jù)交互的場景,比如網(wǎng)站前臺與后臺之間的數(shù)據(jù)交互
?
網(wǎng)址
官方文檔
json — JSON encoder and decoder — Python 3.11.4 documentation
在線解析網(wǎng)站
JSON在線解析及格式化驗證 - JSON.cn
使用
引入
import json
?
json.loads()
把Json字符串解碼為Python數(shù)據(jù)【內(nèi)置四種類型/列表/字典】
str = '123'
print(json.loads(str)) #123
strList = '[1,2,3,4]'
print(json.loads(strList)) ?# [1, 2, 3, 4]\
strDict = '{"city": "北京", "name": "范爺"}'
print(json.loads(strDict)) ?# {'city': '北京', 'name': '范爺'}
如果傳入的字符串的編碼不是UTF-8的話,需要指定字符編碼的參數(shù)
data_dict = json.loads(jsonStrGBK, encoding="GBK");
如果 dataJsonStr通過encoding指定了合適的編碼,但是其中又包含了其他編碼的字符,
則需要先去將dataJsonStr轉(zhuǎn)換為Unicode,然后再指定編碼格式調(diào)用json.loads()
dataJsonStrUni = dataJsonStr.decode("GB2312");
dataDict = json.loads(dataJsonStrUni, encoding="GB2312");
?
json.dumps()
把python數(shù)據(jù)【內(nèi)置四種類型/列表/字典】轉(zhuǎn)化為json字符串
默認(rèn)使用ascii編碼【添加參數(shù) ensure_ascii=False 禁用ascii編碼,按utf-8編碼】
dictStr = {"city": "北京", "name": "范爺"}
print(json.dumps(dictStr, ensure_ascii=False)) ?# {"city": "北京", "name": "范爺"}
?
json.dump()
將Python內(nèi)置類型序列化為json對象后寫入文件
listStr = [{"city": "北京"}, {"name": "范爺"}]
json.dump(listStr, open("listStr.json", "w"), ensure_ascii=False)
dictStr = {"city": "北京", "name": "范爺"}
json.dump(dictStr, open("dictStr.json", "w"), ensure_ascii=False)
?
json.load()
讀取文件中json形式的字符串元素,轉(zhuǎn)化成python類型
strList = json.load(open("listStr.json"))
strDict = json.load(open("dictStr.json")) ?????????