更新JSON文件中的字典

huangapple go评论76阅读模式
英文:

Updating a dictionary in a JSON File

问题

试图更新JSON文件中的特定字典,但无法这样做,因为它只是将一个新字典添加到数据库而不是在字典下面。我尝试过将数据库转换为列表,然后将其追加到列表中,然后将其放入数据库,也尝试过使用update()函数,但两种方式都没有将其添加到字典下面。

英文:

Trying to update a certain dictionary in a json file but unable to do so as it just adds a new dictionary to the database rather than being under the dictionary.
An example, of what I'm trying to achieve is:

Before running the function the database looks like:

{
    "account_details": [
        {
            "Username": "TestingUsername",
            "Password": "232Pass",
            "Email": "TestingEmail@outlook.com",
            "Token": "18973871HIA"
        }
    ]
}

After running the function this is what the database looks like:

{
    "account_details": [
        {
            "Username": "TestingUsername",
            "Password": "232Pass",
            "Email": "TestingEmail@outlook.com",
            "Token": "18973871HIA"
        }
    ]
}{
    "Username": "TestingUsername",
    "Password": "232Pass",
    "Email": "TestingEmail@outlook.com",
    "Token": "18973871HIA",
    "Details": {
        "Preset1": {
            "Username": "TestingUsername",
            "Password": "TestingPassword3",
            "URL": "TestingURL.com:"
        }
    }
}

The functions, function is to take in the Presetname (TestingPreset39), under the Details dictionary, which then includes the Username (Testing_username) , Password (TestingPresetPassword) & Url (preset.com).

However, what I want it to look like is:

{
    "account_details": [
        {
            "Username": "ComputingCourse32",
            "Password": "NoNUmbers",
            "Email": "computingcw@cwl.com",
            "Token": "4L8PWWRFYL",
            "Testing": "Testing",
            "Details": {
                "Preset1": {
                    "Username": "Username1",
                    "Password": "Password1",
                    "URL": "http://testing.cwl.com"
                }
            }
        },

I've tried to convert the database into a list as a way to append to the list then putting it in the database:

   with open("testaccount.json", "r+") as file:
        data = json.load(file)
        for record in data["account_details"]:
            if record["Username"] == username:
                if type(record) is dict:
                    data = [record]
                    # data['specific_dict'].append(new_dict)

                    data.append ({
                        "Details" : {
                        "Preset1":{
                        "Username": "TestingUsername",
                        "Password": "TestingPassword",
                        "URL": "TestingURL.com"
                        }
                        }
                    })
                   
                    print(data)

Also, I've tried to use the update() function:

with open("testaccount.json", "r+") as file:
    data = json.load(file)
    for record in data["account_details"]:
        if record["Username"] == "TestingUsername":
            new_data = {"Details":{
                "Preset1":{
                "Username": "TestingUsername",
                "Password": "TestingPassword3",
                "URL": "TestingURL.com:"
                }
            }}
            record.update(new_data)
            print(record)

Though both ways put the new data in the database neither ways actually add it under the dictionary.

更新JSON文件中的字典

答案1

得分: 1

使用文件中的json格式数据,您不能可靠地覆盖文件的部分。您应该读取整个文件,将更改作为Python对象进行,最后将整个文件重新写入。quamrana

您可以使用以下代码来实现这一点。

with open('testaccount.json', 'r') as f: 
    data = json.load(f)

for ri, record in enumerate(data["account_details"]):
    if record["Username"] == "TestingUsername":
        new_data = {'Details': {'Preset1': {
                    'Username': 'TestingUsername',
                    'Password': 'TestingPassword3',
                    'URL': 'TestingURL.com:'          }}}
        
        data["account_details"][ri].update(new_data)

with open('testaccount.json', 'w') as f: 
    json.dump(data, f, indent=4)

请注意,*record.update(new_data)*不会影响data,因为record只是data["account_details"][ri]的副本。

英文:

> With json format data in a file, you cannot reliably overwrite parts of the file. You should read the entire file, make changes as python objects, and finally write the entire file back.quamrana

You can do so with the code below.<sup>(view result)</sup>

with open(&#39;testaccount.json&#39;, &#39;r&#39;) as f: 
    data = json.load(f)

for ri, record in enumerate(data[&quot;account_details&quot;]):
    if record[&quot;Username&quot;] == &quot;TestingUsername&quot;:
        new_data = {&#39;Details&#39;: {&#39;Preset1&#39;: {
                    &#39;Username&#39;: &#39;TestingUsername&#39;,
                    &#39;Password&#39;: &#39;TestingPassword3&#39;,
                    &#39;URL&#39;: &#39;TestingURL.com:&#39;          }}}
        
        data[&quot;account_details&quot;][ri].update(new_data)
# print(data)

with open(&#39;testaccount.json&#39;, &#39;w&#39;) as f: 
    json.dump(data, f, indent=4)

<sup>Note that record.update(new_data) would not affect data as record is just a copy of data[&quot;account_details&quot;][ri].</sup>

huangapple
  • 本文由 发表于 2023年2月23日 19:34:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/75544268.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定