3

I have the following JSON on which I want to get specific values using SelectToken -

{
  "Result": {
    "Id": "knownvalue0",
    "Name": "Level0",
    "Children": [
      {
        "Name": "Level1",
        "Id": "knownvalue1",
        "Children": [
          {
            "Name": "Level2",
            "Id": "knownvalue2",
            "Children": [
              {
                "Id": "knownvalue3",
                "Name": "Level3",
                "Children": []
              }
            ]
          }
        ]
      }
    ]
  }
}

The structure is recursive and I do not know the depth at runtime. However I do know the Ids and want to verify that the names are correct. So I use a JsonPath like this - Result..[?(@Id=='knownvalue')].Name in jtoken.parse(response).selecttoken(jsonpath) method. A problem is occurring when I am using this jsonpath on knownvalue1 or knownvalue2 i.e -

Result..[?(@Id=='knownvalue1')].Name

I am getting exception - Path is returning multiple tokens. Why is the selecttoken returning multiple tokens even though there is only 1 name with Id = 'knownvalue1'?? The Level2 and Level3 nodes are children, they should not be returned.

6
  • 1
    "Result..Children[?(@Id=='knownvalue1')].Name" works as expected, see dotnetfiddle.net/RvN0Zy. Not sure what's wrong with your query though. Commented Aug 20, 2019 at 18:30
  • 1
    Alternatively, on jsonpath.curiousconcept.com, both Result..[?(@Id=='knownvalue1')].Name and Result..Children[?(@Id=='knownvalue1')].Name generate an error -- but Result..[?(@.Id=='knownvalue1')].Name (and Result..Children[?(@.Id=='knownvalue1')].Name) work as expected when using Flow Communications JSONPath 0.4.0 -- but none work using Goessner. Commented Aug 20, 2019 at 18:43
  • Result..*[?(@Id=='knownvalue1')].Name also works if you don't want to hardcode the name Children. Apparently the recursive descent operator has to terminate in some sort of property name for the subsequent array indexer to behave as expected. Commented Aug 20, 2019 at 19:01
  • Is that a sufficient answer? Commented Aug 20, 2019 at 19:01
  • @dbc - yeah Result..Children worked yesterday as well. Only problem is that the root node itself isn't inside 'Children', so have to write separate one for that. I will try Result..*[...] and get back on this, thank you. Commented Aug 21, 2019 at 6:53

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.