Python脚本以外科手术方式将一个JSON字段替换为另一个
目前,我正在处理一大组JSON文件,格式如下: File00,在时间T1: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": {
{
"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中实现这一点 以下是我为每个文件采取的步骤:
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?