Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
353 views
in Technique[技术] by (71.8m points)

c# - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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());

Here Enumerable.Any() tests to see whether the SelectTokens() query found more than zero results -- i.e., is there at least one entry in the "Key1" array with a "key2" property. It's more efficient than doing Enumerable.Count() since it stops the evaluation as soon as one item is returned.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...