如何将文件中的 string/value 转换为正确的 JSON 并添加新密钥?

How to convert a string/value in a file to a proper JSON and add a new key?

我有一个包含字符串的 JSON 文件。我想用键值对更新我的 JSON 文件,这样我就可以添加与该字符串对应的键。如果只有 string/value,我想这样做。

同时,我想添加一个新列id,其中id是一个数字,会根据提供的文件数量自动更新。

我不知道在那种情况下该怎么做:(
我们如何编写 python 脚本来进行以下更改?

示例:

要使用 Python 中的 JSON 数据和文件,您可以使用 json module。它有以下方法:

  • load-ing JSON 文件中的数据并将它们转换为 Python 个对象
  • dump-ing Python 对象到 JSON 格式的文件

在Python中,JSON被表示为一个普通的字典,所以你只需要从文件中读取字符串,把它变成一个字典,添加任何其他的key-value对你想要的甚至修改数据,然后dump它回到文件。

现在因为你只想做这个转换如果文件只包含一个字符串,你可以先做json.load,然后用isinstance检查它是否已转换为字典。如果是,那么它已经在正确的 JSON 中,因此您无需执行任何操作。如果没有,并且已经转为字符串,则继续处理。

最后,由于您要覆盖同一个文件,请打开 "r+" mode for reading and writing 中的文件。

import json

# Assume script and files are in the same directory
filepaths = [
    "File1.json",  # Contains "I\nhave\na\ncat"
    "File2.json",  # Contains "I\nhave\na\ndream"
    "File3.json",  # Correct JSON
]

# Process each file one-by-one
for file_id, filepath in enumerate(filepaths):
    with open(filepath, "r+") as f:
        contents = json.load(f)
        if isinstance(contents, dict):
            # This is already in JSON, nothing to fix
            continue
        # We need to fix the file
        data = {"id": file_id, "string": contents}
        f.seek(0)
        json.dump(data, f)