python - 在条件下使用 Python 解析/提取嵌套的 JSON 数据

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

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

这是 JSON 文件。我正在尝试从键“AN”中获取值。我希望能够提取诸如“shannoncampbell_znyq1”、“katiekapprelmac”等值,以便这些值 从第二行开始等于数字零。例如,由于 katiekapprelmac 的第二行值(此行的值是 T7)不等于零,我的代码应该将其吐出(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

请帮忙。谢谢

最佳答案

在代码中:

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

关于python - 在条件下使用 Python 解析/提取嵌套的 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54174164/

相关文章:

python - 如何在Python中修复 'ParserGeneratorWarning: 4 shift/reduce conflicts'

javascript - 第二次调用后Json String不显示

javascript - 根据内容提取对象数组

python - 列表实际上如何使用for循环在python中工作?

python - ** 之后的 MetaSerialisable 对象参数必须是映射,而不是 unicode

python - 将列表和 numpy 数组输出到同一文件中

python - 有效地重新计算维数未知的 numpy 数组的梯度

javascript - 我将如何迭代这个 JSON 数据

python - 当应该影响 X 的变量发生变化时,变量 X 不更新

python - 附加到列表字典会增加每个键的值