python - 如何使用 python 将列表中的信息填充到多个 JSON 对象中?
问题描述
本质上,有一个 JSON 对象列表,subfolders
它需要保存来自 2 个文件的信息——一个来自一个名为的列表json_files
,另一个存储在一个名为table_files
.
来自json_files
并且table_files
需要在每个 JSON 对象中按顺序包含一次的信息。
到目前为止,我能够输出我的 JSON 对象列表和要分别保存在这些对象中的信息,但不能以我需要的格式一起输出,这就是问题所在。
我输出subfolders
列表的代码:
subfolders = [ f.path for f in os.scandir(rootdir) if f.is_dir() ]
subfolders = [sub.replace(rootdir + '\\', '') for sub in subfolders]
obj = { conf_name:{} for conf_name in subfolders }
with open('summary.json', 'w') as f:
json.dump(obj, f, indent=2)
我用于输出要存储在子文件夹中的信息json_data
的代码:table_data
json_data = []
for i in json_files:
with open(i) as f:
json_data.append(json.load(f))
table_data = []
for i in table_files:
with open(i) as f:
table_data.append([line.rstrip('\n') for line in f])
combined = []
for j, t in zip(json_data, table_data):
combined.append(j)
combined.extend(t)
with open('summary.json', 'w') as f:
json.dump(combined, f, indent=2)
期望的输出:
{
"subfolder1": {
"json_data": "{content from first json_data file in list}"
"table_data": "content from first table_data file in list"
},
"subfolder2": {
"json_data": "{content from second json_data file in list}"
"table_data": "content from second json_data file in list"
}
}
因此,我想知道如何将所有内容组合在一起以生成我需要的格式。非常感谢任何帮助,谢谢。
编辑:用于获取和json_files
列表table_files
:
for subdir, dirs, files in os.walk(rootdir):
for file in files:
if file.endswith(".json"):
json_files.append(os.path.join(subdir, file))
if file.endswith(".list"):
table_files.append(os.path.join(subdir, file))
解决方案
你可以试试以下方法:
summary = {}
for subdir, dirs, files in os.walk(rootdir):
for file in files:
if file.endswith(".json"):
json_files.append(os.path.join(subdir, file))
if file.endswith(".list"):
table_files.append(os.path.join(subdir, file))
json_data = []
for i in json_files:
with open(i) as f:
json_data.append(json.load(f))
table_data = []
for i in table_files:
with open(i) as f:
table_data.append([line.rstrip('\n') for line in f])
summary[subdir] = {
'json_data': json_data,
'table_data': table_data
}
with open('summary.json', 'w') as f:
json.dump(summary, f, indent=2)
推荐阅读
- c# - 如何在 C# blazer 中的 for 循环内绑定和保存/更新输入复选框
- javascript - 为什么在 for-of 循环中从未调用过“throw”迭代器接口方法?
- python - 如何将此 yfinance 数据转换为 pandas 数据框?
- php - 如何在php中使流可搜索?
- python - 如何在 Pygame 中按住“按键”?
- php - 条件数组输出插入另一个数组
- javascript - 为每个对象获取不同的随机生成链接
- c# - C#:文件夹未显示在当前命名空间中
- javascript - 如何在 react-redux 连接函数中处理 Refs
- c++ - 使用循环填充 char* 数组