Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python脚本以外科手术方式将一个JSON字段替换为另一个_Python_Json - Fatal编程技术网

Python脚本以外科手术方式将一个JSON字段替换为另一个

Python脚本以外科手术方式将一个JSON字段替换为另一个,python,json,Python,Json,目前,我正在处理一大组JSON文件,格式如下: File00,在时间T1: { "AAA": { "BBB": { "000": "value0" }, "CCC": { "111": "value1", "222": "value2", "333": "value3" }, "DDD": { "444": "value4" } } { "AAA": { "BBB": {

目前,我正在处理一大组JSON文件,格式如下:

File00,在时间T1

{
  "AAA": {
    "BBB": {
      "000": "value0"
    },
    "CCC": {
      "111": "value1",
      "222": "value2",
      "333": "value3"
    },
    "DDD": {
      "444": "value4"
    }
}
{
  "AAA": {
    "BBB": {
      "000": "value0"
    },
    "CCC": {
      "111": "value1",
      "222": "value2",
      "333": "value3"
    },
    "DDD": {
      "666": "value6",
      "007": "value13"
    }
}
在这种情况下,现在我有了子字段“DDD”的新输入,我想“批发”用以下内容替换它:

    "DDD": {
      "666": "value6",
      "007": "value13"
    }
因此,该文件将更改为:

File00,在时间T2

{
  "AAA": {
    "BBB": {
      "000": "value0"
    },
    "CCC": {
      "111": "value1",
      "222": "value2",
      "333": "value3"
    },
    "DDD": {
      "444": "value4"
    }
}
{
  "AAA": {
    "BBB": {
      "000": "value0"
    },
    "CCC": {
      "111": "value1",
      "222": "value2",
      "333": "value3"
    },
    "DDD": {
      "666": "value6",
      "007": "value13"
    }
}
在我遇到的情况下,有许多文件类似于File00,因此我正在努力创建一个脚本,该脚本可以处理特定目录中的所有文件,标识JSON字段
DDD
,并用新内容替换它的内容


如何在Python中实现这一点

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

  • 阅读json
  • 将其转换为Python dict
  • 编辑Python dict
  • 将其转换回json
  • 将其写入文件
  • 重复
  • 这是我的密码:

    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)
    
    此外,我还从您可能希望的目录中获得了用于迭代的代码:

    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)
    

    可能的重复不确定是否适合提及,但我编写了一个库来实现这一点:您可能会从中获得一些灵感?那么,JSON是任意嵌套的吗?或者这就是它的实际情况?同样,JSON可以包含列表,还是只包含dict?