所以如果我有一個 json 存盤用戶資訊,例如
{
"joe": [
{
"name": "joe",
"age": "28",
"height": "",
"Password": ""
}
] }
如何更改或附加資訊,以便我可以添加資訊或使用 python 更改它,例如,我得到 177 的高度輸入 如何使用 python 將其添加到 data["joe"][0]["height"]
uj5u.com熱心網友回復:
只需將值分配給它
data = {"joe": [{"name": "joe", "age": "28", "height": "", "Password": ""}]}
data["joe"][0]["height"] = 177
print(data)
# {'joe': [{'name': 'joe', 'age': '28', 'height': 177, 'Password': ''}]}
您的格式很奇怪,名稱鍵的想法很好,但是陣列的想法很奇怪,似乎沒有添加任何東西
uj5u.com熱心網友回復:
您可以使用json.loads()將 JSON 資料轉換為字典,然后像往常一樣修改字典:
import json
json_data = """{
"joe": [
{
"name": "joe",
"age": "28",
"height": "",
"Password": ""
}
] }"""
data_as_dictionary = json.loads(json_data)
data_as_dictionary['joe'][0]['height'] = input()
print(data_as_dictionary)
uj5u.com熱心網友回復:
您應該從 json 中洗掉該陣列。使用名稱作為鍵并不是一個好主意,如果有 2 個相同的名稱怎么辦?
json檔案:
{"joe": [{"name": "joe", "age": "28", "height": "", "Password": "" }]}
Python代碼:
from json import load, dump
with open('json_file', 'r') as f:
users = load(f)
# with load() you store json data into a dictionary, you can check by printing type()
users['joe'][0]['height'] = 177
with open('json_file', 'w') as f:
dump(users, f)
# with dump() you are storing new data into the json file
編輯:順便說一句,您可能會同時看到加載和加載,加載中的 s 代表“字串”,它用于從字串加載 json 資料,例如,加載用于從檔案加載 json 資料。轉儲和轉儲也是如此
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/452094.html
