Using jsonpath-ng to extract keys and values with conditional matches

914 views Asked by At

I have a data structure like this and want to extract nested data using conditional expressions.

from jsonpath_ng.ext import parse

ex = {
    "data": {
        "a": {
            "id": 1,
            "selected": False,
            "content": {
                "text": "foo"
            }
        },
        "b": {
            "id": 2,
            "selected": True,
            "content": {
                "text": "bar"
            }
        },
        "c": {
            "id": 3,
            "selected": True,
            "content": {
                "text": "foobar"
            }
        }
    }
}

for m in parse("data[?selected==true].content.text").find(ex):
    print(m.full_path, m.value)

What I get is

data.[1].content.text bar
data.[2].content.text foobar

But what I expected and need is

data.b.content.text bar
data.c.content.text foobar

How can I do the conditional match and also get the information if "a", "b", or "c" was selected? It is okay to use a different library than jsonpath-ng. But I don't want to code a function myself that does a post processing with the index in the path or iterate over .keys() and do all that processing that jsonpath-ng is supposed to do.

0

There are 0 answers