【问题标题】:How to merge multiple json in python如何在python中合并多个json
【发布时间】:2016-04-17 23:25:37
【问题描述】:

我有一个包含多个这样的 json 字符串的列表

a = [{"name": "Alex"},{"Age": 25},{"Address": "16, Mount View"}]

我想像这样将它们合并到一个数组中

a = [{"name": "Alex","Age": 25,"Address": "16, Mount View"}]

我曾尝试使用 jsonmerge,但在使用 head' andbase` 值时它无法正常工作。

谁能帮帮我。

我在堆栈中也遇到了类似的问题,但它显示了单独的 json 合并,而不是列表中的 json How to merge two json

【问题讨论】:

标签: python json merge


【解决方案1】:

首先,这些是 python dicts

[{"name": "Alex"},{"Age": 25},{"Address": "16, Mount View"}]

你可以对它们调用 json.dumps 并将它们变成“json 字符串”。

2、可以使用dict更新方法

a =  [{"name": "Alex"},{"Age": 25},{"Address": "16, Mount View"}]
d = {}
for small_dict in a:
    d.update(small_dict)
print(d) # Yay!
a = [d]

请注意! ,如果您有重复的键,它们将相互覆盖

也可以看看“ChainMap”

https://docs.python.org/3/library/collections.html#collections.ChainMap

【讨论】:

  • 有没有办法不替换重复的键?
  • 使用反向列表会给你 - a[::-1] (它只是从头到尾替换:))
  • 我如何使用反向列表,我应该使用它作为for small_dict in -a:
  • @TonyRoczz - 用于 a[::-1] 中的 small_dict:
【解决方案2】:

要添加到@yoav glazner 的答案,如果您使用的是 Python 3.3+,则可以使用ChainMap

>>> from collections import ChainMap
>>> a = [{"name": "Alex"},{"Age": 25},{"Address": "16, Mount View"}]
>>> dict(ChainMap(*a))
{'name': 'Alex', 'Age': 25, 'Address': '16, Mount View'}

在此处查看有关ChainMap 用例的更多信息:

【讨论】:

    猜你喜欢
    • 2019-03-19
    • 2017-12-28
    • 2019-12-16
    • 2019-01-20
    • 2018-04-09
    • 1970-01-01
    • 2020-04-11
    • 1970-01-01
    • 2022-12-07
    相关资源
    最近更新 更多