I have an issue using NewtonSoft v8.0.3 JToken.SelectTokens() with a specific JsonPath. To reproduce issue in C#:
string json = "[{\"name\":\"string\",\"value\":\"aString\"},{\"name\":\"number\",\"value\":123},{\"name\":\"array\",\"value\":[1,2,3,4]},{\"name\":\"object\",\"value\":{\"1\":1}}]";
string path = "$.[?(@.value!=null)]";
string newJson = String.Empty;
JToken jt = JToken.Parse(json);
IEnumerable<JToken> tokens = jt.SelectTokens(path, false);
newJson = JsonConvert.SerializeObject(tokens, Formatting.Indented);
// Output is missing objects and arrays??
// newJson = [{"name": "string","value": "aString"},{"name": "number","value": 123}]
Running above code will not return any objects or arrays?! Is there a bug in JToken.SelectTokens() of Json.Net?
To validate the path I have used http://goessner.net/articles/JsonPath/ which works fine, see this working fiddle
I hope someone can shine some light on this.
UPDATE: Thought this issue occured as we are trying to use "null" value, but no matter what inequality query I run, no {} / [] is returned from JSON.
Finally figured out what was causing the .SelectTokens to ignore arrays and objects when using JSONPath. The issues occurs in QueryExpressions.cs line 78
JValue v = r as JValue;
This will cause any JToken that is JObject/JArray to become null and hence being ignored when compared. My way of fixing this was to replace line 78 with the following code that handles JObject and JArray:
JValue v = null;
switch (r.Type)
{
case JTokenType.Object:
case JTokenType.Array:
v = new JValue(r.ToString());
break;
default:
v = r as JValue;
break;
}
This will ensure that JObject and JArray are returned when calling .SelectTokens. Please feel free to comment solution or suggest alternative and better aproaches.
UPDATE: Happy to inform that this issue been fixed with new releases. See GITHUB for more information.