如何将文件中的 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 脚本来进行以下更改?
示例:
- File1.json 包含
"I\nhave\na\ncat"
预期输出:(File1.json)
{id: "1", string :"I\nhave\na\ncat"}
- File2.json
"I\nhave\na\ndream"
预期输出:(File2.json)
{id: "2", string :"I\nhave\na\ndream"}
要使用 Python 中的 JSON 数据和文件,您可以使用 json
module。它有以下方法:
在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)
我有一个包含字符串的 JSON 文件。我想用键值对更新我的 JSON 文件,这样我就可以添加与该字符串对应的键。如果只有 string/value,我想这样做。
同时,我想添加一个新列id
,其中id
是一个数字,会根据提供的文件数量自动更新。
我不知道在那种情况下该怎么做:(
我们如何编写 python 脚本来进行以下更改?
示例:
- File1.json 包含
预期输出:(File1.json)"I\nhave\na\ncat"
{id: "1", string :"I\nhave\na\ncat"}
- File2.json
预期输出:(File2.json)"I\nhave\na\ndream"
{id: "2", string :"I\nhave\na\ndream"}
要使用 Python 中的 JSON 数据和文件,您可以使用 json
module。它有以下方法:
在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)