代码之家  ›  专栏  ›  技术社区  ›  gordon sung

在条件下用python解析/提取嵌套的json数据

  •  4
  • gordon sung  · 技术社区  · 6 年前

    我正试图从JSON文件的细节中提取/解析值,我做了一个POST请求。

    这是JSON文件。我正在尝试从键“an”中获取值。我希望能够提取值,例如“ 香农坎贝尔 “,” 凯蒂卡普利马克 “,等,以便 从第二排 等于零。例如,由于第二行的值(此行的 T7 的) 凯蒂卡普利马克 不等于零,我的代码应该把它吐出来( 凯蒂卡普利马克 应该是输出)。但事实并非如此。

    JSON文件:

    {
    "id": "jsonrpc",
    "jsonrpc": "2.0",
    "result": {
        "result": [
            {
                "AccountId": 697429,
                "Flags": [
                    "AutoDeployed"
                ],
                "PartnerId": 287562,
                "Settings": [
                    {
                        "AN": "shannoncampbell_znyq1"
                    },
                    {
                        "T7": "0"
                    }
                ]
            },
            {
                "AccountId": 725177,
                "Flags": null,
                "PartnerId": 287562,
                "Settings": [
                    {
                        "AN": "katiekapprelmac"
                    },
                    {
                        "T7": "5"
                    }
                ]
            },
            {
                "AccountId": 689130,
                "Flags": [
                    "AutoDeployed"
                ],
                "PartnerId": 287562,
                "Settings": [
                    {
                        "AN": "sara-pc_wpv7h"
                    },
                    {
                        "T7": "0"
                    }
                ]
            },
            {
                "AccountId": 697531,
                "Flags": null,
                "PartnerId": 287562,
                "Settings": [
                    {
                        "AN": "kaelaweeksmac"
                    },
                    {
                        "T7": "0"
                    }
                ]
            },
            {
                "AccountId": 615877,
                "Flags": null,
                "PartnerId": 249098,
                "Settings": [
                    {
                        "AN": "elenimacbookpro"
                    },
                    {
                        "T7": "0"
                    }
                ]
            },
            {
                "AccountId": 700661,
                "Flags": null,
                "PartnerId": 287562,
                "Settings": [
                    {
                        "AN": "sethnickersonmac"
                    },
                    {
                        "T7": "0"
                    }
                ]
            },
    

    下面是我的python代码:

    response2 = requests.request("POST", url, data=payload2, headers=headers)
    
    j = json.loads(response2.text) 
    
    
    def find_all(item, level):
        if isinstance(item, dict):
            for k in item:
                (find_all(item[k], level+1))
        else:
            print(item)
    
    
    def find_only(item, level):
        if isinstance(item, dict):
            for k in item:
                (find_only(item[k], level+1))
    
    
    for each in j['result']['result']:
        if (find_only(each['Settings'][1], 0)) != json.loads("0"):
            find_all(each['Settings'][0], 0)
    

    相反,我得到输出中的所有键。我得到以下信息:

    shannoncampbell_znyq1
    katiekapprelmac
    sara-pc_wpv7h
    kaelaweeksmac
    elenimacbookpro
    sethnickersonmac
    

    而不仅仅是 凯蒂卡普利马克

    请帮忙。谢谢

    2 回复  |  直到 6 年前
        1
  •  1
  •   Zishan Khan    6 年前

    在代码中:

    for each in j['result']['result']:
    if (find_only(each['Settings'][1], 0)) != json.loads("0"):
        find_all(each['Settings'][0], 0)
    

    我真的看到了,你的情况总是 True ,因为你没有归还任何东西 find_only() .

    我不知道,为什么要使用级别和这么多递归函数。尽管根据你发布的数据很容易提取结果。请在下面找到代码。

    response2 = requests.request("POST", url, data=payload2, headers=headers)
    j = json.loads(response2.text)
    for each in j['result']['result']:
    if each['Settings'][1]['T7'] not in ["0", 0]:
        print(each['Settings'][0]['AN'])
    

    如果你的回答数据有点复杂,那么请发布准确的解决方案。

    如果您有多个密钥名,请查看以下代码:

    response2 = requests.request("POST", url, data=payload2, headers=headers)
    j = json.loads(response2.text)
    
    def find_all(item):
        if isinstance(item, dict):
            for k in item:
                return item[k]
        # If item is non dict and you want to return this as well on `True`.
        # Uncomment below commented lines.
        # else:
        #     item
    def find_only(item):
        if isinstance(item, dict):
            for k in item:
                return item[k]
    
    for each in j['result']['result']:
        if (find_only(each['Settings'][1])) != str(json.loads("0")):
            print(find_all(each['Settings'][0]))
    
        2
  •  1
  •   Frans    6 年前

    jsonpath ng可以帮助您实现这一点。

    from jsonpath_ng.ext import parse
    
    found = parse(f"$..Settings").find(data)
    if found:
        for i in found:
            if ''.join(i.value[1].values()) != '0':
                print(i.value[0]['AN'])