Yuv
Yuv

Reputation: 33

How to use SelectToken() when a property name contains indexer characters []

Trying to edit a JSON object, I have to get to a specific node. I am using something like:

root.SelectToken("dot.delimited.path.to.node")

and it works fine until a node has a property name like "vectorOne[1]".

Is there a way to 'escape' the [] characters in SelectToken()? if not- can someone please advice?

Upvotes: 1

Views: 1367

Answers (1)

dbc
dbc

Reputation: 117284

As explained in the original JSONPath proposal, you can use bracket notation as well as dot notation for accessing properties by name:

JSONPath expressions can use the dot–notation

$.store.book[0].title

or the bracket–notation

$['store']['book'][0]['title']

Thus, using SelectToken(), you may access a property named "vectorOne[1]" via ['vectorOne[1]']. E.g., if your JSON looks like:

{
  "data": {
    "vectorOne[1]": {
      "value": 1
    }
  }
}

Then

root.SelectToken("data['vectorOne[1]'].value")

Will select the value 1.

Notes:

  • If the property name contains an single-quote character, it can be escaped with a \, e.g. if you have the following JSON:

    {
      "single-quote-'": "value"
    }
    

    Then you may select the "single-quote-'" by using the following path:

    root.SelectToken(@"['single-quote-\'']");
    

    (Be careful not to confuse c# string escaping, which is evaluated at compile time, with JSONPath string escaping, which is evaluated at runtime.)

  • If you are uncertain of the path to use for any specific value, you can iterate through all the descendants of a JObject using JContainer.DescendantsAndSelf() and print their paths via JToken.Path:

     foreach (var item in root.DescendantsAndSelf())
         Console.WriteLine(item.Path);
    
  • See also the documentation page Querying JSON with JSON Path and escaped properties.

Demo fiddle here.

Upvotes: 1

Related Questions