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

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

Append to a json file using python

问题

  1. 尝试向嵌套的json文件追加内容
  2. 我的目标是向一个JSON文件中追加一些值
  3. 这是我的原始JSON文件
  4. {
  5. "web": {
  6. "all": {
  7. "side": {
  8. "tags": [
  9. "admin"
  10. ],
  11. "summary": "Generates",
  12. "operationId": "Key",
  13. "consumes": [],
  14. "produces": [
  15. "application/json"
  16. ],
  17. "responses": {
  18. "200": {
  19. "description": "YES",
  20. "schema": {
  21. "type": "string"
  22. }
  23. }
  24. },
  25. "Honor": [
  26. {
  27. "presidential": []
  28. }
  29. ]
  30. }
  31. }
  32. }
  33. }
  34. 我打算在键Honor内添加两行额外的内容值分别为Required:YESPrepay:NO”。追加这两个值后我将得到以下JSON文件
  35. {
  36. "web": {
  37. "all": {
  38. "side": {
  39. "tags": [
  40. "admin"
  41. ],
  42. "summary": "Generates",
  43. "operationId": "Key",
  44. "consumes": [],
  45. "produces": [
  46. "application/json"
  47. ],
  48. "responses": {
  49. "200": {
  50. "description": "YES",
  51. "schema": {
  52. "type": "string"
  53. }
  54. }
  55. },
  56. "Honor": [
  57. {
  58. "presidential": [],
  59. "Required" : "YES",
  60. "Prepay" : "NO"
  61. }
  62. ]
  63. }
  64. }
  65. }
  66. }
  67. 以下是我编写的Python代码
  68. ```python
  69. import json
  70. def write_json(data,filename ="exmpleData.json"):
  71. with open(filename,"w") as f:
  72. json.dump(data,f,indent=2)
  73. with open ("exmpleData.json") as json_files:
  74. data= json.load(json_files)
  75. temp = data["Honor"]
  76. y = {"required": "YES","type": "String"}
  77. temp.append(y)
  78. write_json(data)

我收到以下错误消息:

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

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

  1. <details>
  2. <summary>英文:</summary>
  3. Trying to append to a nested json file
  4. My goal is to append some values to a JSON file.
  5. 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": []
}
]
}
}

  1. }

}

  1. 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"
}
]
}
}

  1. }

}

  1. 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)

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

  1. import json
  2. def write_json(data, filename=&#39;exmpleData.json&#39;):
  3. with open(filename, &#39;w&#39;) as f:
  4. json.dump(data, f, indent=2)
  5. with open(&#39;exmpleData.json&#39;) as json_files:
  6. data = json.load(json_files)
  7. # &#39;Honor&#39; is deeply nested in other dictionaries
  8. honor = data[&#39;web&#39;][&#39;all&#39;][&#39;side&#39;][&#39;Honor&#39;]
  9. # Its value is a 1-element list containing another dictionary.
  10. honor[0][&#39;Required&#39;] = &#39;YES&#39;
  11. honor[0][&#39;Prepay&#39;] = &#39;NO&#39;
  12. 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:

确定