将多个不同层数的嵌套字典写入特定格式的JSON文件中
我有一个包含不同层数的多个字典的列表。它是这样的:
data_ls = [
{"a": {"b": {"c1": {"d1": "d1_value"}}}},
{"a": {"b": {"c2": {"d2": {"e1": "e1_value "}}}}},
...
...
]
我需要将它写入一个 JSON 文件,这是我尝试过的:
json_str = json.dumps(data_ls)
json_file = open("data.json", "w")
json_file.write(json_str)
输出将是这样的:
[
{
"a": {
"b": {
"c1": {
"d1": "d1_value"
}
}
}
},
{
"a": {
"b": {
"c2": {
"d2": {
"e1": "e1_value "
}
}
}
}
}
]
但是一些相同的键被证明是分开嵌套的,所需的输出看起来像:
[{
"a": {
"b": {
"c1": {"d1": "d1_value"},
"c2": {
"d2": {"e1": "e1_value "},
},
}
}
}]
How do I得到这样的输出? 提前致谢!
I have a list of multiple dictionaries with different numbers of layers. Here's what it looks like:
data_ls = [
{"a": {"b": {"c1": {"d1": "d1_value"}}}},
{"a": {"b": {"c2": {"d2": {"e1": "e1_value "}}}}},
...
...
]
I need to write it to a JSON file, here's what I tried:
json_str = json.dumps(data_ls)
json_file = open("data.json", "w")
json_file.write(json_str)
The output will be like:
[
{
"a": {
"b": {
"c1": {
"d1": "d1_value"
}
}
}
},
{
"a": {
"b": {
"c2": {
"d2": {
"e1": "e1_value "
}
}
}
}
}
]
But some of the same keys are turned out to be separated nested, the desired output looks like:
[{
"a": {
"b": {
"c1": {"d1": "d1_value"},
"c2": {
"d2": {"e1": "e1_value "},
},
}
}
}]
How do I get the output like this?
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以一次对两个字典使用递归函数,检查键是否存在,如果不更新键
输出:
注意:
You can use a recursive function with two dictionaries at a time, checking whether the key exists or not if not update the key
Output:
Note: