【问题标题】:How to get value from JSON - Python如何从 JSON 中获取价值 - Python
【发布时间】: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


【解决方案1】:

在 pyzer 的帮助下,我找到了解决问题的方法。代码是这样的:

# Request to get all UltimateParent
def checkParent(murex):
    for item in murex:
        cdwParenturl = f"http://cdwu/cdw/counterparties/{item}/?yyyy-mm-dd={dateinplay}"

        r = requests.get(cdwParenturl).json()
        clientref = r[0]["riskUltimateParent"]["identifier"][1]
        
        if clientref == "":
           print(colored(f"The parent {item} does not have ultimateParent", "red"))
        else:
            print(colored(f"All counterparties have parent", "green")) 

checkParent(r_mheu_trade)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-03
    • 2013-04-11
    • 1970-01-01
    • 1970-01-01
    • 2021-04-24
    • 1970-01-01
    • 2021-09-02
    • 1970-01-01
    相关资源
    最近更新 更多