fractal
fractal

Reputation: 43

JSON.net SelectToken() with single quote in path

Consider this json:

{
    "farms": [
        {
            "fred's": {
                "cows": 5,
                "pigs": 2,
                "horses": "none"
            }
        }, {
            "old mcdonald's": {
                "cows": none,
                "pigs": 1,
                "horses": 3
            }
        }
    ]
}

There seems to be no problem with using single quotes alone:

JObject j = new JObject();
JToken jt = j.SelectToken(farms.fred's);

However, errors occur when trying to use both single quotes and white spaces.

Using this code:

JObject j = new JObject();
JToken jt = j.SelectToken(farms.old mcdonald's);

I got this error:

JsonException: Unexpected character while parsing path

So I did some searching and found that terms with white spaces must be surrounded by:

[' ']

Example:

JObject j = new JObject();
JToken jt = j.SelectToken(farms.['old mcdonald's']);

However, now the error is:

JsonException: Unexpected character while parsing path indexer: s

Is it possible to include both white spaces and single quotes in the SelectToken path?

Upvotes: 4

Views: 2816

Answers (1)

Brian Chavez
Brian Chavez

Reputation: 8573

Seems so...

var x = @"{
    ""farms"": [
        {
            ""fred's"": {
                ""cows"": 5,
                ""pigs"": 2,
                ""horses"": ""none""
            }
        },
        {
            ""old mcdonald's"": {
                ""cows"": ""none"",
                ""pigs"": 1,
                ""horses"": 3
            }
        }
    ]
}";

var j = JObject.Parse(x);
var jobj = j.SelectToken("farms[1]['old mcdonald\\'s']") as JObject;
jobj.Properties().Select( p => p.Name + ": " + p.Value).Dump();

IEnumerable<String> (3 items)
* cows: none 
* pigs: 1 
* horses: 3 

Upvotes: 4

Related Questions