mooglinux mooglinux - 3 months ago 15
JSON Question

Testing for nested keys with Json.NET?

I want to filter a reactive stream of json encoded strings like this:

{ "Key1" : {"key2":"value"},
"key3" : "other values"
}


I want to filter for items that have some value for
key2
, like this:

IDisposable valueQuery = globalEventStream
.Select(e => JObject.Parse(e.EventArgs.Data))
.Where(e => e["key1"]["key2"] != null)


But this gives me the error

Cannot access child value on Newtonsoft.Json.Linq.JValue


The only way I can find to get around this is to do the following:

IDisposable deathDisposable = globalEventStream
.Select(e => JObject.Parse(e.EventArgs.Data))
.Where(e => e["key1"] != null).Select(e => e["key1"])
.Where(e => e["key2"] != null).Select(e => e["key2"])


Is there a way to filter for nested keys with a single
Where
statement?

dbc dbc
Answer

You can use JToken.SelectTokens() to run nested queries on LINQ to JSON objects:

var valueQuery = globalEventStream
    .Select(e => JObject.Parse(e.EventArgs.Data))
    .Where(o => o.SelectTokens("Key1.key2").Any());

Sample fiddle.

The specification for JSONPath is here and supports the following query syntax:

XPath   JSONPath    Description
/       $            the root object/element
.       @           the current object/element
/       . or []     child operator
..      n/a         parent operator
//      ..          recursive descent. JSONPath borrows this syntax from E4X.
*       *           wildcard. All objects/elements regardless their names.
@       n/a         attribute access. JSON structures don't have attributes.
[]      []          subscript operator. XPath uses it to iterate over element collections and for predicates. In Javascript and JSON it is the native array operator.
|       [,]         Union operator in XPath results in a combination of node sets. JSONPath allows alternate names or array indices as a set.
n/a     [start:end:step]    array slice operator borrowed from ES4.
[]      ?()         applies a filter (script) expression.
n/a     ()          script expression, using the underlying script engine.
()      n/a         grouping in Xpath 

E.g., for the following JSON:

{ "Key1" : [{"NoKey2":"value"}, {"key2":"value"}],  "key3" : "other values" }

You could use the wildcard operator * to test for the presence of any item in the array with a "key2" property as follows:

var valueQuery = globalEventStream
    .Select(e => JObject.Parse(e.EventArgs.Data))
    .Where(o => o.SelectTokens("Key1[*].key2").Any());
Comments