使用Json.NET测试嵌套键? [英] Testing for nested keys with Json.NET?
问题描述
我想过滤像这样的json编码字符串的反应流:
I want to filter a reactive stream of json encoded strings like this:
{ "Key1" : {"key2":"value"},
"key3" : "other values"
}
我想过滤具有key2
值的项目,例如:
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)
但这给了我错误
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"])
是否有一种方法可以通过单个Where
语句来过滤嵌套键?
Is there a way to filter for nested keys with a single Where
statement?
推荐答案
您可以使用 JToken.SelectTokens()
在LINQ上运行嵌套查询到JSON对象:
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());
示例小提琴.
JSONPath的规范是此处,并且支持以下查询语法:
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
例如,用于以下JSON:
E.g., for the following JSON:
{ "Key1" : [{"NoKey2":"value"}, {"key2":"value"}], "key3" : "other values" }
您可以使用通配符*
来测试具有"key2"
属性的数组中是否存在任何项目,如下所示:
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());
在 Enumerable.Any()
中进行测试以查看SelectTokens()
查询发现了不止零个结果-即"Key1"
数组中至少有一个具有"key2"
属性的条目.它比做 Enumerable.Count()
效率更高,因为它会立即停止评估作为一项退回.
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.
这篇关于使用Json.NET测试嵌套键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!