json如何使用python编辑条目用户信息



所以如果我有一个存储用户信息的json,例如


{
"joe": [
{
"name": "joe",
"age": "28",
"height": "",
"Password": ""
}
] }

如何更改或附加信息,以便我可以使用python添加信息或更改信息,例如,我得到177的高度输入如何使用python 将其添加到数据["joe"][0]["height"]

只需将值分配给

data = {"joe": [{"name": "joe", "age": "28", "height": "", "Password": ""}]}
data["joe"][0]["height"] = 177
print(data)
# {'joe': [{'name': 'joe', 'age': '28', 'height': 177, 'Password': ''}]}

您的格式很奇怪,名称键的想法很好,但数组的想法很奇怪,它似乎没有添加任何

您可以使用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)

您应该从json中删除数组。使用名称作为关键字并不是一个好主意,如果有两个相同的名称怎么办?

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数据,load用于从文件中加载例如json数据。转储和转储也是如此

最新更新