Reputation: 43
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
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