使用Python将内容追加到一个JSON文件中

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

Append to a json file using python

问题

尝试向嵌套的json文件追加内容

我的目标是向一个JSON文件中追加一些值

这是我的原始JSON文件

{
    "web": {
        "all": {
          "side": {
            "tags": [
              "admin"
            ],
            "summary": "Generates",
            "operationId": "Key",
            "consumes": [],
            "produces": [
              "application/json"
            ],
            "responses": {
              "200": {
                "description": "YES",
                "schema": {
                  "type": "string"
                }
              }
            },
            "Honor": [
              {
                "presidential": []
              }
            ]
          }
        }

    }
}

我打算在键Honor内添加两行额外的内容值分别为Required:YESPrepay:NO”。追加这两个值后我将得到以下JSON文件

{
    "web": {
        "all": {
          "side": {
            "tags": [
              "admin"
            ],
            "summary": "Generates",
            "operationId": "Key",
            "consumes": [],
            "produces": [
              "application/json"
            ],
            "responses": {
              "200": {
                "description": "YES",
                "schema": {
                  "type": "string"
                }
              }
            },
            "Honor": [
              {
                "presidential": [],
                "Required" : "YES",
                "Prepay"   : "NO"
              }
            ]
          }
        }

    }
}

以下是我编写的Python代码

```python
import json
def write_json(data,filename ="exmpleData.json"):
    with open(filename,"w") as f:
        json.dump(data,f,indent=2)
with open ("exmpleData.json") as json_files:
    data= json.load(json_files)
    temp = data["Honor"]
    y = {"required": "YES","type": "String"}
    temp.append(y)
write_json(data)

我收到以下错误消息:

** temp = data["Honor"] KeyError: 'Honor' **

我将不胜感激地接受您提供的任何指导,以帮助我实现我的目标。我正在运行Python 3.7


<details>
<summary>英文:</summary>
Trying to append to a nested json file 
My goal is to append some values to a JSON file. 
Here is my original JSON file

{
"web": {
"all": {
"side": {
"tags": [
"admin"
],
"summary": "Generates",
"operationId": "Key",
"consumes": [],
"produces": [
"application/json"
],
"responses": {
"200": {
"description": "YES",
"schema": {
"type": "string"
}
}
},
"Honor": [
{
"presidential": []
}
]
}
}

}

}

It is my intention to add two additional lines inside the key &quot;Honor&quot;, with the values &quot;Required&quot; : &quot;YES&quot; and &quot;Prepay&quot; : &quot;NO&quot;. As a result of appending the two values, I will have the following JSON file.

{
"web": {
"all": {
"side": {
"tags": [
"admin"
],
"summary": "Generates",
"operationId": "Key",
"consumes": [],
"produces": [
"application/json"
],
"responses": {
"200": {
"description": "YES",
"schema": {
"type": "string"
}
}
},
"Honor": [
{
"presidential": [],
"Required" : "YES",
"Prepay" : "NO"
}
]
}
}

}

}

Below is the Python code that I have written

import json
def write_json(data,filename ="exmpleData.json"):
with open(filename,"w") as f:
json.dump(data,f,indent=2)
with open ("exmpleData.json") as json_files:
data= json.load(json_files)
temp = data["Honor"]
y = {"required": "YES","type": "String"}
temp.append(y)
write_json(data)

I am receiving the following error message:
** temp = data[&quot;Honor&quot;] KeyError: &#39;Honor&#39; 
**
I would appreciate any guidance that you can provide to help me achieve my goal. I am running Python 3.7
</details>
# 答案1
**得分**: 1
'`Honor`' 深度嵌套在其他字典中,其值是包含一个字典的 1 元素列表。以下是如何访问:
```py
import json
def write_json(data, filename='exmpleData.json'):
with open(filename, 'w') as f:
json.dump(data, f, indent=2)
with open('exmpleData.json') as json_files:
data = json.load(json_files)
# 'Honor' 深度嵌套在其他字典中
honor = data['web']['all']['side']['Honor']
# 其值是包含另一个字典的 1 元素列表
honor[0]['Required'] = 'YES'
honor[0]['Prepay'] = 'NO'
write_json(data)
英文:

&#39;Honor&#39; is deeply nested in other dictionaries, and its value is a 1-element list containing a dictionary. Here's how to access:

import json

def write_json(data, filename=&#39;exmpleData.json&#39;):
    with open(filename, &#39;w&#39;) as f:
        json.dump(data, f, indent=2)

with open(&#39;exmpleData.json&#39;) as json_files:
    data = json.load(json_files)
    # &#39;Honor&#39; is deeply nested in other dictionaries
    honor = data[&#39;web&#39;][&#39;all&#39;][&#39;side&#39;][&#39;Honor&#39;]
    # Its value is a 1-element list containing another dictionary.
    honor[0][&#39;Required&#39;] = &#39;YES&#39;
    honor[0][&#39;Prepay&#39;] = &#39;NO&#39;

write_json(data)

答案2

得分: 1

我建议你再练习一下基础知识,因为在处理数据结构时你犯了许多错误。好消息是,你的JSON加载/转储是正确的。

你的错误消息的原因是数据没有一个名为"Honor"的属性。数据只有一个名为"web"的属性,其中包含一个名为"all"的属性,其中包含一个名为"side"的属性,其中包含一个名为"Honor"的属性,其中包含一个包含你要添加的属性的字典的数组。因此,你可以使用以下方式将temp设置为temp = data['web']['all']['side']['Honor'][0]

你也不能在Python字典上使用append。相反,查看dict.update()

英文:

I'd recommend that you practice your fundamentals a bit more since you're making many mistakes in your data structure handling. The good news is, your JSON load/dump is fine.

The cause of your error message is that data doesn't have an "Honor" property. Data only has a "web" property, which contains "all" which contains "side" which contains "Honor", which contains an array with a dictionary that holds the properties you are trying to add to. So you want to set temp with temp = data[&#39;web&#39;][&#39;all&#39;][&#39;side&#39;][&#39;Honor&#39;][0]

You also cannot use append on python dictionaries. Instead, check out dict.update().

huangapple
  • 本文由 发表于 2023年2月6日 10:07:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/75356784.html
匿名

发表评论

匿名网友

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

确定