json.loads()
json.loads 用于解碼 JSON 數(shù)據(jù),將Json格式字符串解碼轉(zhuǎn)換成Python對象
import json
arr = [1, 2, 3, 4]
print(json.loads(str(arr)))
dic = '{"name": "xiaoming", "age": 18}'
print(json.loads(dic))
#[1, 2, 3, 4]
#{'name': 'xiaoming', 'age': 18}
json.dumps()
把一個Python對象編碼轉(zhuǎn)換成Json字符串
import json
arr = [1, 2, 3, 4]
print(json.dumps(arr))
dic = {"name": "xiaoming", "age": 18}
print(json.dumps(dic))
json.dump()
將Python內(nèi)置類型序列化為json對象后寫入文件,ensure_ascii比較關鍵,True代表顯示為編碼形式,這個一般在中文里面特別不好用,所以建議關掉
import json
dic = {"name": "xiaohong", "age": 18}
json.dump(dic, open('json.txt', 'w'), ensure_ascii=False)
json.load()
讀取文件中json形式的字符串元素 轉(zhuǎn)化成python類型
import json
dic = {"name": "xiaohong", "age": 18}
json.dump(dic, open('json.txt', 'w'), ensure_ascii=False)
content = json.load(open('json.txt'))
print(type(content), content)