2

I'm new to Json.NET and try out using the SelectToken function.

My test JSON:

{
  "Root": {
    "aNode": {
      "bNode": {
        "cNode": {
          "id": "myID1"
        }
      },
      "cNode": {
        "id": "myID2"
      },
      "dNode": {
        "cNode": [
          {
            "id": "myID3"
          },
          {
            "id": "myID4"
          }
        ]
      }
    },
    "cNode": {
      "id": "myID5"
    }
  }
}

Now, I'm trying to use the following code for getting specific objects:

JObject obj = JsonConvert.DeserializeObject<JObject>(jsonTxt);

//Not found
var myID1 = obj.SelectToken("..cNode[?(@.id=='myID1')]");

//Not found
var myID2 = obj.SelectToken("..cNode[?(@.id=='myID2')]");

//Found
var myID3 = obj.SelectToken("..cNode[?(@.id=='myID3')]");

//Found
var myID4 = obj.SelectToken("..cNode[?(@.id=='myID4')]");

//Not found
var myID5 = obj.SelectToken("..cNode[?(@.id=='myID5')]");

Why do I get these (for me) strange results?

I think I should get in every case the cNode object with the specific ID, and not only myID3 and myID4. What's wrong here?

1 Answer 1

3

I am not sure what you really want to achieve but you can use Linq to get cNodes

var nodes = obj.Descendants()
                .OfType<JProperty>()
                .Where(p => p.Name == "id")
                .Select(p=>p.Parent)
                .ToList();
Sign up to request clarification or add additional context in comments.

1 Comment

I want to get the cNode with a specific "id". Let's say "myID1". (p => p.Name == "id" && p.Value == "myID1") Thanks for the answer, but I would like to know the correct JPath.

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.