【发布时间】:2021-12-18 13:45:27
【问题描述】:
如果有人可以帮助我从 json 响应中获取值。我打算只获得类型为 CLIENTREF 的 id 的第一次出现。 我正在阅读一个列表以获取一些值来执行 GET 并检查响应是否不是 null ""。
这是 JSON 结构:
这是我目前的代码
def checkParent(list):
for item in list:
cdwParenturl = f"http://cdwu/cdw/counterparties/{item}/?yyyy-mm-dd={dateinplay}"
r = requests.get(cdwParenturl).json()
jsonpath_expression = parse("$..identifier[*]")
# $..identifier[?(@.type == 'CLIENTREF')].id
parentId = []
for match in jsonpath_expression.find(r):
# print(f"match id: {match.value}")
thisdict = match.value
if thisdict["type"] == "CLIENTREF":
# print(thisdict["id"])
parentId.append(thisdict["id"])
elif thisdict["id"] == "":
print(colored(f"The parent {item} does not have ultimateParent", "red"))
print(colored(f"All counterparties have parent", "green"))
checkParent(r_mheu_trade)
print(f "match id: {match.value}") 我明白了,我需要的是与类型相关的第一个id:CLIENTREF
我的控制台上出现的错误是这样的:
Traceback (most recent call last):
File "h:\DESKTOP\test_check\checkCounterpartie.py", line 114, in <module>
checkParent(r_mheu_trade)
File "h:\DESKTOP\test_check\checkCounterpartie.py", line 106, in checkParent
if thisdict["type"] == "CLIENTREF":
KeyError: 'type'
【问题讨论】:
-
请避免在你的情况下使用关键字作为变量名,如
list。假设你的json文件被分配给名为json1的变量,你会通过这种方式到达CLIENTREFjson1[0]['riskUltimateParent']['identifier'][1] -
非常感谢pyzer的回复,这解决了我的问题。
标签: python json list rest xpath