Search code examples
jmespath

How to get list of all child elements with field from parent


I have list of dicts that contains another list in one of fields. I want to "flatten" that list, so it gives me every subelement with one field (or some fields) from parent copied into it. Example:

Source data:

[
    {
        "name": "A",
        "foo": "x",
        "bar": 1,
        "subelements": [
            {
                "baz": "xyz",
                "foobar": "abc"
            },
            {
                "baz": "zzz",
                "foobar": "def"
            }
        ]
    },
    {
        "name": "B",
        "foo": "Y",
        "bar": 4,
        "subelements": [
            {
                "baz": "yyy",
                "foobar": "aaa"
            },
            {
                "baz": "xxx",
                "foobar": "bbb"
            },
            {
                "baz": "www",
                "foobar": "bbb"
            }
        ]
    }
]

Expected result:

[
    {
        "baz": "xyz",
        "foobar": "abc",
        "foo": "x"
    },
    {
        "baz": "zzz",
        "foobar": "def",
        "foo": "x"
    },
    {
        "baz": "yyy",
        "foobar": "aaa",
        "foo": "Y"
    },
    {
        "baz": "xxx",
        "foobar": "bbb",
        "foo": "Y"
    },
    {
        "baz": "www",
        "foobar": "bbb",
        "foo": "Y"
    }
]

Solution

  • This is not currently possible to do without parent node reference. Parent node access is still listed as a feature request