我有下面的列表,我必须从中检索port
号,我想要的值是50051
,但得到的是port=50051
,我知道我可以通过迭代列表来检索并使用字符串操作,但希望查看是否有直接方法可以访问它。
r = requests.get(url_service)
data = {}
data = r.json()
#Below is the json after printing
[{'ServerTag': [ 'abc-service=true',
'port=50051',
'protocol=http']
}]
print(data[0]["ServiceTags"][1]) // prints port=50051
答案 0 :(得分:0)
您也许可以执行以下操作:
received_dic = {
'ServerTag': [ 'abc-service=true',
'port=50051',
'protocol=http']
}
ServerTag = received_dic.get("ServerTag", None)
if ServerTag:
port = list(filter(lambda x: "port" in x, ServerTag))[0].split("=")[1]
print(port)
# 50051
答案 1 :(得分:0)
考虑到您拥有以下JSON:
[
{
"ServerTag": ["abc-service=true", "port=50051", "protocol=http"]
}
]
您可以像这样提取您的值:
from functools import partial
# ...
def extract_value_from_tag(tags, name, default=None):
tags = map(partial(str.split, sep='='), tags)
try:
return next(value for key, value in tags if key == name)
except StopIteration:
# Tag was not found
return default
然后您就可以:
# Providing data is the deserialized JSON as a Python list
# Also assuming that data is not empty and ServerTag is present on the first object
tags = data[0].get('ServerTag', [])
port_number = extract_value_from_tag(tags, 'port', default='8080')