【问题标题】:Python script to surgically replace one JSON field by anotherPython 脚本以手术方式将一个 JSON 字段替换为另一个
【发布时间】:2017-11-16 23:40:50
【问题描述】:

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

File00,时间 T1

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

现在我有一个新的输入子字段"DDD",我想“批发”用以下内容替换它:

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

相应地,文件将更改为:

File00,时间 T2

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

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

如何在 Python 中做到这一点?

【问题讨论】:

  • 不确定是否合适提及,但我写了一个库来做到这一点:github.com/erewok/pelecanus你也许能从中得到一些启发?
  • 那么,JSON是任意嵌套的吗?或者这就是它的本来面目?
  • 另外,JSON 可以包含列表,还是只包含字典?

标签: python json


【解决方案1】:

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

  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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-17
    • 2012-10-24
    • 2016-11-06
    • 2019-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多