Magic Lava
Magic Lava

Reputation: 59

How do I find a JSON object using a nested expression?

From the example JSON below, I would like to return the target.id value of an object where the source.id == 'x'.

So where source.id == 'startId' return target.id == '3eecd840-e6a8-423c-a892-7df9646fde5d'.

{
      "line":[
         {
            "type":"link",
            "source":{
               "id":"startId",
               "port":"out"
            },
            "target":{
               "id":"3eecd840-e6a8-423c-a892-7df9646fde5d",
               "port":"in"
            },
            "id":"87d88a26-3a28-4db0-8016-71c1c4665f14"

         },
         {
            "type":"link",
            "source":{
               "id":"3eecd840-e6a8-423c-a892-7df9646fde5d",
               "port":"outYes"
            },
            "target":{
               "id":"49940c02-70f2-4c53-ab50-9cbf96903600",
               "port":"in"
            },
            "id":"9f8c365e-9ca7-440f-a722-c4f340782c0c"
         }
      ]
   }

I've tried JSONPath, but I cannot work out the expression to use. $.line[*].source.id gives me a list of source id's and $.line[?(@.source.id=='startId')] returns an error.

I also understand that I could iterate through each object in code, but It wouldn't be very efficient if I have tens or hundreds of 'lines' to work through. If possible I would like a more 'direct' path to the object.

I'm using javascript to code the rest of the app, so javascript examples would be helpful (with or without JSONPath).

Upvotes: 0

Views: 331

Answers (1)

Amit Joki
Amit Joki

Reputation: 59232

If you're getting json as string, then use var json = JSON.parse(jsonStr). Then you can do it with Array.filter

var result = json.line.filter(function(obj){
   return obj.source.id == "startId"
});

Then you could get the values like this

var ids = result.map(function(o){ return o.target.id });

Upvotes: 1

Related Questions