我有一个服务urlA,如果我打电话给我,它会在json响应下面给我,其中包含由数据中心键入的服务器列表。将来,我可以拥有更多的密钥,并且每个密钥都有更多的服务器。
{
"abc": ["goldy11.abc.host.com", "goldy12.abc.host.com"],
"pqr": ["goldy21.pqr.host.com", "goldy22.pqr.host.com"],
"def": ["goldy31.def.host.com", "goldy32.def.host.com"],
"jhk": ["goldy41.jhk.host.com", "goldy42.jhk.host.com"]
}
类似地,我还有另一个服务urlB,它给出类似的响应,但服务器集不同:
{
"abc": ["goldy81.abc.host.com", "goldy82.abc.host.com"],
"pqr": ["goldy91.pqr.host.com", "goldy92.pqr.host.com"],
"def": ["goldy71.def.host.com", "goldy72.def.host.com"],
"jhk": ["goldy51.jhk.host.com", "goldy52.jhk.host.com"]
}
我想从两个网址的上述json响应中提取所有服务器名称,如下所示:
goldy11.abc.host.com
goldy12.abc.host.com
goldy21.pqr.host.com
goldy22.pqr.host.com
goldy31.def.host.com
goldy32.def.host.com
goldy41.jhk.host.com
goldy42.jhk.host.com
goldy81.abc.host.com
goldy82.abc.host.com
goldy91.pqr.host.com
goldy92.pqr.host.com
goldy71.def.host.com
goldy72.def.host.com
goldy51.jhk.host.com
goldy52.jhk.host.com
所以我像这样开始,但是对于如何通过解析两个服务网址中的json响应而不以硬编码方式指定任何键来提取所有服务器,我有些困惑?
import json
import requests
responsea = requests.get("service-url-a")
responseb = requests.get("service-url-b")
json_data_a = json.loads(responsea.text)
json_data_b = json.loads(responseb.text)
# how can I combine both json_data_a and json_data_b response in the hosts list
hosts = [value for value_set in json_data_a.values() for value in value_set]
print hosts
答案 0 :(得分:1)
您想要展平阵列。具有以下内容:
hosts = [value for value_set in json_data.values() for value in value_set]
这将为您提供所有主机的列表。然后,您可以从那里继续其余的任务。
答案 1 :(得分:1)
>>> import json
>>> a = """{
... "abc": ["goldy11.abc.host.com", "goldy12.abc.host.com"],
... "pqr": ["goldy21.pqr.host.com", "goldy22.pqr.host.com"],
... "def": ["goldy31.def.host.com", "goldy32.def.host.com"],
... "jhk": ["goldy41.jhk.host.com", "goldy42.jhk.host.com"]
... }"""
>>> b = """{
... "abc": ["goldy81.abc.host.com", "goldy82.abc.host.com"],
... "pqr": ["goldy91.pqr.host.com", "goldy92.pqr.host.com"],
... "def": ["goldy71.def.host.com", "goldy72.def.host.com"],
... "jhk": ["goldy51.jhk.host.com", "goldy52.jhk.host.com"]
... }"""
>>> data_a = json.loads(a)
>>> data_b = json.loads(b)
>>> print(json.dumps([value for values in list(data_a.values()) + list(data_b.values()) for value in values], indent=True))
[
"goldy21.pqr.host.com",
"goldy22.pqr.host.com",
"goldy11.abc.host.com",
"goldy12.abc.host.com",
"goldy41.jhk.host.com",
"goldy42.jhk.host.com",
"goldy31.def.host.com",
"goldy32.def.host.com",
"goldy91.pqr.host.com",
"goldy92.pqr.host.com",
"goldy81.abc.host.com",
"goldy82.abc.host.com",
"goldy51.jhk.host.com",
"goldy52.jhk.host.com",
"goldy71.def.host.com",
"goldy72.def.host.com"
]