GibboK
GibboK

Reputation: 74008

How to find parentNode from childNode in a JSON structure using jsonPath or an alternative?

I need to find out a parentNode from childNode in a JSON structure. For example I need to know what is the parent for "view_id": "f".

I am evaluating jsonPath but I cannot find a parent operator.

I would like to now:

You can test JSON structure here: http://jsonpath.curiousconcept.com/

[
    {
        "view_id": "a",
        "views": [
            {
                "view_id": "b",
                "views": [
                    {
                        "view_id": "c"
                    },
                    {
                        "view_id": "d"
                    }
                ]
            },
            {
                "view_id": "e",
                "views": [
                    {
                        "view_id": "f"
                    },
                    {
                        "view_id": "g"
                    }
                ]
            },
            {
                "view_id": "h"
            }
        ]
    },
    {
        "view_id": "i",
        "views": [
            {
                "view_id": "l",
                "views": [
                    {
                        "view_id": "m",
                        "views": [
                            {
                                "view_id": "n"
                            },
                            {
                                "view_id": "o"
                            }
                        ]
                    }
                ]
            },
            {
                "view_id": "p"
            }
        ]
    },
    {
        "view_id": "q"
    }
]

Upvotes: 1

Views: 5359

Answers (1)

GibboK
GibboK

Reputation: 74008

I found two possible solutions to this specif problem as for my understanding jsonPath does not allow me to find the parent for a node:

Solution A:

  • Adding a property "parent_id" to every node in the JSON, query the JSON using jsonPath.

Solution B:

  • Not using jsonPath for this task and instead keeping an in memory rap-presentation of the JSON as a "flat" array, when populating the array I can add to each node a "parent_id" as to find a child node I always need to know its parent (as suggested from comments). Any search is done on the "flat" array using JS.

Upvotes: 3

Related Questions