Bisjob
Bisjob

Reputation: 828

c# Newtonsoft : get json token with name containing special character

I have some Json files containing special character like this :

{
  "someProperties" : "someValues",
  "$ROOT_QUERY.searchResults({\"path\":\"/some/url\"}).features": 
  {
    "propertyOtherA": "valueA",
    "propertyOtherB": "null",
  },
  "$ROOT_QUERY.searchResults({\"path\":\"/some/url\"}).otherText": 
  {
    "propertyOtherA": "valueA",
    "propertyOtherB": "null",
  }
}

How can I set the token path to get it ? When I try the standard path, I get a Unexpected character exception

string path = "$ROOT_QUERY.searchResults({\\\"path\\\":\\\"" + request.RequestUri.PathAndQuery + "\\\"})";
var token = jObject.SelectToken("$." + path + ".features");

I also tried to replace string in Json, but the string.Contains method is not returning true, whereas it works fine in notepad. I also tried simple Regex, but i've not succed to make it work. My last idea is atomic Regex, but before entering to this hell, I'm trying to ask you if I can any chance to get it with a simplier way.

Thank you

Upvotes: 0

Views: 1103

Answers (1)

OfirD
OfirD

Reputation: 10460

You need to escape path using '[]' - note that .features should also be included:

var path = "['$ROOT_QUERY.searchResults({\"path\":\"" + request.RequestUri.PathAndQuery + "\"}).features']";
var token = jObject.SelectToken("$." + path);
Console.WriteLine(token);

You need to escape this entire path, because you have multiple "reserved" characters there: $, ., () (see this non-oficial documentation). See other escaping examples here.

demo.

Upvotes: 3

Related Questions