davej
davej

Reputation: 1380

json.net SelectToken with embedded "."

I have json that looks like:

myjson = {"queries":{"F.SP": 27}}

so with

queryResults = JObject.Parse(jsonString)

I can do

firstToken = queryResults.SelectToken("queries") 

and get back the LinqJToken

{"F.SP": 27}

but I'm then stuck, because when I try

subToken = firstToken.SelectToken("F.SP")

I get Nothing. I'm guessing this is because JSON.net is looking for a token "F" with subtoken "SP".

I've also tried each of the following, to no avail

myToken = queryResults.SelectToken("queries.F.SP")     
myToken = queryResults.SelectToken("queries[0].F.SP")     

(queryResults.SelectToken("queries[0]") returns nothing, fwiw)

Any ideas?

EDIT: I have verified that the embedded "." is the problem; if I change the original json to

{"queries":{"FSP": 27}}

I can do

queryResults.SelectToken("queries").SelectToken("FSP")

no problem

Upvotes: 8

Views: 4213

Answers (4)

Anton
Anton

Reputation: 143

If you have such names in JSON fields:

{"queries":{"F.SP": 27}}

You may use SelectToken escaping:

queryResults.SelectToken("queries").SelectToken("['F.SP']")

or

queryResults.SelectToken("queries.['F.SP']")

Here are more examples with escaping: http://www.newtonsoft.com/json/help/html/QueryJsonSelectTokenEscaped.htm

Upvotes: 5

duyn9uyen
duyn9uyen

Reputation: 10311

Instead of trying to use SelectToken, how about an index search?

subToken = queryResults["F.SP"];

Upvotes: 1

Erik Porter
Erik Porter

Reputation: 2326

This won't return the token itself, but will return the value (which is probably what you're looking for anyway)...

queryResults.SelectToken("queries").Value<int>("F.SP");

Upvotes: 4

gdp
gdp

Reputation: 8252

JObject obj = JObject.Parse(jsonstring);
var fsp = obj["queries"].First().First();

Not the most elegant but it gets the value.

Upvotes: 0

Related Questions