作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
目前我正在处理大量以下形式的 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 中执行此操作?
最佳答案
以下是我对每个文件采取的步骤:
这是我的代码:
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/
这个问题已经有答案了: 已关闭10 年前。 Possible Duplicate: Real world use cases of bitwise operators 我不太确定按位运算符&和| ,有
我是一名优秀的程序员,十分优秀!