Python:将嵌套字典合并到一个JSON中

kg7wmglp  于 2022-11-19  发布在  Python
关注(0)|答案(1)|浏览(221)

如何将JSON的yield生成器中的字符串合并到一个JSON中?
我已经通过yield生成器得到了嵌套字典,我的目标是有一个JSON文件。
我已经输出了这些嵌套字典的正确字符串。

{"domain.com": {"Chrome": "19362.344607264396"}}
{"domain.com": {"ChromeMobile": "7177.498437391487"}}
{"another.com": {"MobileSafari": "6237.433155080214"}}
{"another.com": {"Safari": "5895.409403430795"}}

我想合并成一个JSON文件

[
  {
    "domain.com": {
      "Chrome": "19362.344607264396"
    }
  },
  {
    "domain.com": {
      "ChromeMobile": "7177.498437391487"
    }
  },
  {
    "another.com": {
      "MobileSafari": "6237.433155080214"
    }
  },
  {
    "another.com": {
      "Safari": "5895.409403430795"
    }
  }
]

或者理想情况下使用类似于此的JSON

{
  "browsers": [
    {
      "domain.com": {
        "Chrome": "19362.344607264396",
        "ChromeMobile": "7177.498437391487",
      },
      "another.com": {
        "MobileSafari": "6237.433155080214",
        "Safari": "5895.409403430795"
      }
    }
  ]
}

我的代码
第一个
有一个最终输出。

# Get a list of domains and substitution each one into a request of Prometheus query.
for domain_list in domain_zones():
    for dict in browser_map_page_views(domain_zone=domain_list):
        dicts = dict
        print(json.dumps(dicts))
cu6pst1q

cu6pst1q1#

像这样的东西

import json

DATA = [
    {"domain.com": {"Chrome": "19362.344607264396"}},
    {"domain.com": {"ChromeMobile": "7177.498437391487"}},
    {"another.com": {"MobileSafari": "6237.433155080214"}},
    {"another.com": {"Safari": "5895.409403430795"}}
]

def yield_data():
    for d in DATA:
        yield d

def merge1():
    return list(yield_data())

def merge2():
    output = {}
    for d in DATA:
        key = list(d.keys())[0]
        output[key] = output.get(key, {})
        output[key].update(d[key])
    
    return {"browsers": [output]}

print(json.dumps(merge1(), indent=2))
print(json.dumps(merge2(), indent=2))

merge1的输出如下所示:

[
  {
    "domain.com": {
      "Chrome": "19362.344607264396"
    }
  },
  {
    "domain.com": {
      "ChromeMobile": "7177.498437391487"
    }
  },
  {
    "another.com": {
      "MobileSafari": "6237.433155080214"
    }
  },
  {
    "another.com": {
      "Safari": "5895.409403430795"
    }
  }
]

merge2的输出如下

{
  "browsers": [
    {
      "domain.com": {
        "Chrome": "19362.344607264396",
        "ChromeMobile": "7177.498437391487"
      },
      "another.com": {
        "MobileSafari": "6237.433155080214",
        "Safari": "5895.409403430795"
      }
    }
  ]
}

相关问题