Take the following valid json:
{
"universe": {
"solar system": "sun"
}
}
and here's the simple C# code:
using Newtonsoft.Json;
JToken x = JToken.Parse("{\"universe\": {\"solar system\": \"sun\"}}");
string s = x.First.First.First.Path;
At this point s = "universe['solar system']"
However I'm expecting "universe.['solar system']"
(notice the '.' after "universe").
If the json key does not have a space ("solar_system") I get "universe.solar_system"
which is correct.
The question is: Is this a bug in json.net or do I need to do something else to support spaces in json keys?
Thanks,
PT
This is not a bug. The path returned by JToken.Path
is intended to be in JSONPath syntax. As explained in the original JSONPath proposal:
JSONPath expressions can use the dot–notation
$.store.book[0].title
or the bracket–notation
$['store']['book'][0]['title']
So universe['solar system']
is perfectly valid, and if you pass it to SelectToken()
you'll get the correct value "sun"
back:
JToken x = JToken.Parse("{\"universe\": {\"solar system\": \"sun\"}}");
string path = x.First.First.First.Path;
Console.WriteLine(path); // Prints universe['solar system']
var val = (string)x.SelectToken(path);
Console.WriteLine(val); // Prints "sun"
Debug.Assert(val == "sun"); // No assert
See also Querying JSON with SelectToken and escaped properties.
If you nevertheless want the extra .
in the path you can create your own extension method JTokenExtensions.ExpandedPath(this JToken token)
based on the reference source.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With