adinas
adinas

Reputation: 4550

Using Newtonsoft.Json. How to do JObject.SelectToken when token name is "['token_name']"?

Using Newtonsoft.Json I have the following JSON

{"['token_name']":"0.00"}

Trying

string s = "{\"['token_name']\":\"0.00\"}";
jsonObj = JObject.Parse(s);
myPJObject.SelectToken("['token_name']")

returns null. I've tried all kinds of variations like

myPJObject.SelectToken("[\"['token_name']\"]")

But could not find one that works.

How do I select this token?

Upvotes: 1

Views: 1004

Answers (2)

Brian Rogers
Brian Rogers

Reputation: 129667

Another possible solution is to use the indexer instead of SelectToken to handle this case:

var myPJObject = jsonObj["['token_name']"];

This works because the indexer does not use JsonPath syntax; it always takes the verbatim property name.

Fiddle: https://dotnetfiddle.net/chNG3E

Upvotes: 1

Guru Stron
Guru Stron

Reputation: 141755

This should do it:

jsonObj.SelectToken(@"['[\'token_name\']']")

JObject has Path property (you can try jsonObj.First.Path for your code) which in this case will return "['[\'token_name\']']" string, all is left is to handle the ecape \ characters with verbatim string prefix for example.

Upvotes: 1

Related Questions