【问题标题】:Add text to the end of multiple json files将文本添加到多个 json 文件的末尾
【发布时间】:2022-01-18 03:23:05
【问题描述】:

我对编程很陌生,所以请原谅任何可怕的解释。基本上我有 1000 个 json 文件,所有这些文件都需要在末尾添加相同的文本。这是一个例子:

这就是现在的样子:

{"properties": {
    "files": [
      {
        "uri": "image.png",
        "type": "image/png"
      }
    ],
    "category": "image",
    "creators": [
      {
        "address": "wallet address",
        "share": 100
      }
    ]
  }
}

我希望看起来像这样:

 {"properties": {
    "files": [
      {
        "uri": "image.png",
        "type": "image/png"
      }
    ],
    "category": "image",
    "creators": [
      {
        "address": "wallet address",
        "share": 100
      }
    ]
  },
    "collection": {"name": "collection name"}
}

我已经尽力使用追加和更新,但它总是告诉我没有要追加的属性。我也不知道自己在做什么。

这会很尴尬,但这是我尝试过但失败的方法。

import json

entry= {"collection": {"name": "collection name"}}

for i in range((5)):
  a_file = open("./testjsons/" + str(i) + ".json","r")
  json_obj = json.load(a_file)
  print(json_obj)

json_obj["properties"].append(entry)
a_file = open(str(i) + ".json","w")
json.dump(json_obj,a_file,indent=4)
a_file.close() 
json.dump(a_file, f)

错误代码:json_obj["properties"].append(entry) AttributeError: 'dict' 对象没有属性 'append'

【问题讨论】:

  • 包括您尝试过的代码和任何错误
  • 这不是一个有效的 JSON 文件。周围必须有{ }
  • 你不应该使用append。只是object['collection'] = {'name': collection_name} 其中object 是您从json.load 获得的对象
  • 我知道,它只是json文件的一部分。
  • 如您所见,collection 不在properties 对象内。

标签: python json metadata


【解决方案1】:

您不使用append() 添加到字典。您可以分配给键以添加单个条目,也可以使用.update() 来合并字典。

import json

entry= {"collection": {"name": "collection name"}}

for i in range((5)):
    with open("./testjsons/" + str(i) + ".json","r") as a_file:
        a_file = open("./testjsons/" + str(i) + ".json","r")
        json_obj = json.load(a_file)
        print(json_obj)
        
    json_obj.update(entry)
    with open(str(i) + ".json","w") as a_file:
        json.dump(json_obj,a_file,indent=4)

【讨论】:

  • 这很接近。我在“属性”之外需要它,所以分配给键?
  • 我更新了答案以更新主对象而不是properties
【解决方案2】:

JSON 和 XML 一样,是一种特殊的数据格式。您应该始终解析数据并尽可能将其作为 JSON 使用。这与您将“添加到末尾”或“附加”文本的纯文本文件不同。

Python 中有许多 json 解析库,但您可能希望使用标准 Python 库中内置的 json encoder。对于文件myfile.json,您可以:

import json
with open('myfile.json`, 'r') as f:
    myfile = json.load(f) # read the file into a Python dict
    myfile["collection"] = {"name": "collection name"} # here you're adding the "collection" field to the end of the Python dict
# If you want to add "collection" inside "properties", you'd do something like
#.  myfile["properties"]["collection"] = {"name": "collection name"}

with open('myfile.json', 'w') as f:
    json.dump(myfile, f) # save the modified dict into the json file

【讨论】:

    猜你喜欢
    • 2013-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-08
    • 2021-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多