gpt4 book ai didi

Python 脚本通过手术将一个 JSON 字段替换为另一个字段

转载 作者:行者123 更新时间:2023-12-01 02:26:27 34 4
gpt4 key购买 nike

目前我正在处理大量以下形式的 JSON 文件:

文件00,时间T1:

{
"AAA": {
"BBB": {
"000": "value0"
},
"CCC": {
"111": "value1",
"222": "value2",
"333": "value3"
},
"DDD": {
"444": "value4"
}
}

现在的情况是,我在子字段“DDD”中有一个新输入,我想将“批发”替换为以下内容:

    "DDD": {
"666": "value6",
"007": "value13"
}

相应地,文件将更改为:

文件00,时间T2:

{
"AAA": {
"BBB": {
"000": "value0"
},
"CCC": {
"111": "value1",
"222": "value2",
"333": "value3"
},
"DDD": {
"666": "value6",
"007": "value13"
}
}

在我遇到的情况下,有很多个类似于File00的文件,所以我正在努力创建一个可以处理中所有文件的脚本特定目录,识别 JSON 字段 DDD 并用新内容替换其内容。

如何在 Python 中执行此操作?

最佳答案

以下是我对每个文件采取的步骤:

  1. 读取 json
  2. 将其转换为 Python 字典
  3. 编辑 Python 字典
  4. 将其转换回 json
  5. 将其写入文件
  6. 重复

这是我的代码:

import json

#list of files.
fileList = ["file1.json", "file2.json", "file3.json"]

for jsonFile in fileList:
# Open and read the file, then convert json to a Python dictionary
with open(jsonFile, "r") as f:
jsonData = json.loads(f.read())

# Edit the Python dictionary
jsonData["AAA"]["DDD"]={"666": "value6","007": "value13"}

# Convert Python dictionary to json and write to the file
with open(jsonFile, "w") as f:
json.dump(jsonData, f)

另外,我从 here. 获得了迭代目录的代码您可能想要这样的东西:

import os

directory = os.fsencode(directory_in_str)

for file in os.listdir(directory):
filename = os.fsdecode(file)
if filename.endswith(".json"):
fileList.append(filename)

关于Python 脚本通过手术将一个 JSON 字段替换为另一个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47341000/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com