pts4
pts4

Reputation: 499

Newtonsoft JSON.NET and spaces in json key bug?

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

Upvotes: 4

Views: 2953

Answers (1)

dbc
dbc

Reputation: 116554

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.

Upvotes: 6

Related Questions