json格式:
[{
"name": "Bob",
"gender": "male",
"birthday": "1992-10-18"
}, {
"name": "Selina",
"gender": "female",
"birthday": "1995-10-18"
}]
讀取Json:
json庫實現對json文件的讀寫操作,調用json庫的loads()方法將Json文本字符串轉爲Json對象,可以通過dumps()方法將Json對象轉爲文本字符串:
import json
content = """
[{
"name": "Bob",
"gender": "male",
"birthday": "1992-10-18"
}, {
"name": "Selina",
"gender": "female",
"birthday": "1995-10-18"
}]
"""
print(type(content)) #輸出類型
content = json.loads(content) #json 類型轉換成list類型
for i in content:
print(i["name"])
print(type(content))
print(content)
注意: Json 的數據需要用雙引號來包圍,不能使用單引號,不然會拋出如下錯誤
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 3 column 5 (char 8)
輸出json:
# 利用dumps()方法將json對象轉化爲字符串,然後使用write()方法寫入文本中
import json
content = [{
'name': '天使',
'gender': '女',
'birthday': '1992-10-18'
}]
with open('test2.json','w',encoding='utf-8') as f:
f.write(json.dumps(content,ensure_ascii=False,indent=2))
#如果json中包含中文字符,爲了保證輸出正文,需要指定一個參數ensure_ascii=False,另外還需要指定文件輸出的編碼