0
votes

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).

1
Any reason you can't just parse the JSON and then work with the resulting object graph? (Which isn't JSON, it's an object graph. JSON is a textual notation.) From your question, it sounds like you're working with JSON as text... - T.J. Crowder
Despite its name, JSONPath still seems to work with the parsed object, not the JSON string. So it also iterates over the object. - Felix Kling
Yes I start off with JSON as a string and then create an object using JSON.parse(x). JSONPath allows me to slice json up , but doesnt seem to allow me to pick an object value based on another object value, ie. pick the 'target' where the 'source' = foo - Magic Lava

1 Answers

1
votes

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 });