如何使用jsonpath_ng解析JSON中的嵌套信息

u5i3ibmn  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(248)

我有以下JSON,它来自一个API响应:

{
    "expand": "names,schema",
    "startAt": 0,
    "maxResults": 50,
    "total": 3,
    "issues": [
        {
            "expand": "",
            "id": "10001",
            "self": "http://www.example.com/10001",
            "key": "ABC-1",
            "fields": [
                {
                    "From":"Ibiza",
                    "To":"Mallorca"
                },                
                {
                    "From":"Mallorca",
                    "To":"Miami"
                }
            ]
        },
        {
            "expand": "",
            "id": "10002",
            "self": "http://www.example.com/10002",
            "key": "ABC-2",
            "fields": [
                {
                    "From":"NYC",
                    "To":"Charlotte"
                },                
                {
                    "From":"Charlotte",
                    "To":"Los Angeles"
                },
                {
                    "From":"Los Angeles",
                    "To":"San Diego"
                }
            ]
        },
        {
            "expand": "",
            "id": "10003",
            "self": "http://www.example.com/10003",
            "key": "ABC-3",
            "fields": [
                {
                    "From":"Denver",
                    "To":"Boson"
                }
            ]
        }
    ]
}

字符串

目标

我的目标是在Python中打印一个组合列表,如:

10001 - Ibiza - Mallorca
10001 - Mallorca - Miami
10002 - NYC - Charlotte
10002 - Charlotte - Los Angeles
10002 - Los Angeles - San Diego
10003 - Denver - Boston

我所做的

下面的代码段运行良好,但我真的不明白如何合并信息。我明白我应该将整个JSON拆分为更小的部分,每个项目一个,然后应用第二个和第三个捕获.有人能帮助我吗?

import jsonpath_ng.ext as jp
import json

data=json.loads(response.text)

# 1st catch: 10001,10002,10003
query = jp.parse("$.issues[*].id")
for match in query.find(data):
    key=match.value
    print(key)

#2nd catch: Ibiza, Mallorca, NYC, ...
query = jp.parse("$.issues[*].fields[*].From")
for match in query.find(data):
    key=match.value
    print(key)

#3nd catch: Mallorca, Miami, Charlotte, ...
query = jp.parse("$.issues[*].fields[*].To")
for match in query.find(data):
    key=match.value
    print(key)

ljo96ir5

ljo96ir51#

我真的不知道那个软件包,但我用过一个类似的jmespath。基于它,我可能会尝试:

results = [
    f"{parent.value['id']} - {child.value['From']} -{child.value['To']}"
    for parent in jp.parse("$.issues[*]").find(data)
    for child in jp.parse("$.fields[*]").find(parent.value)
]

for result in results:
    print(result)

字符串

相关问题