【问题标题】:parsing/extracting nested JSON data with Python under Conditions在条件下使用 Python 解析/提取嵌套的 JSON 数据
【发布时间】:2019-06-08 00:10:44
【问题描述】:

我正在尝试从我执行发布请求的 JSON 文件中的细节中提取/解析值。

这是 JSON 文件。我正在尝试从键“AN”中获取值。我希望能够提取诸如“shannoncampbell_znyq1”、“katiekapprelmac”等值,这样的值 从第二行 等于数字零。例如,由于 katiekapprelmac 的第二行值(该行的值是 T7)不等于 0,我的代码应该将其吐出(katiekapprelmac 应该是输出)。然而事实并非如此。

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

而不仅仅是katiekapprelmac

请帮忙。谢谢

【问题讨论】:

标签: python json python-3.x python-2.7 python-requests


【解决方案1】:

在代码中:

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() 中没有返回任何内容。

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

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】:

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'])

【讨论】:

    猜你喜欢
    • 2018-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-10
    • 1970-01-01
    相关资源
    最近更新 更多