猿问

使用 JsonPath 从 JSON 数组中选择项目,其中项目不包含某个属性

我有一个类似于此的 JSON 文件结构:


{

    "property1": 1,

    "property2": 2,

    "someArray": [

        {

            "item1": 1,

            "item2": 2

        },

        {

            "item1": 5

        }

    ]

}

我想要做的就是从不包含item2属性的数组中选择对象。我正在使用NewtonsoftJson并尝试使用 JSON 路径来做这件事。


我设法选择了包含item2属性的对象,但我不知道反转逻辑的语法。


// Selects all the tokens where item2 property exists.

var tokens = jsonToken.SelectTokens("$.someArray[?(@.item2)]");

我尝试!在过滤器部分使用这样的: $.someArray[?(!@.item2),但它抛出一个错误,说这!是意外的字符。


我应该怎么做才能在这里反转选择逻辑?


慕码人8056858
浏览 459回答 2
2回答

慕容3067478

想出了这个方法。希望能帮助到你。工作示例static string jonsString = (@"{&nbsp; &nbsp; &nbsp; &nbsp; 'property1': 1,&nbsp; &nbsp; &nbsp; &nbsp; 'property2': 2,&nbsp; &nbsp; &nbsp; &nbsp; 'someArray': [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'item1': 1,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'item2': 2&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'item1': 5,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'item2': 2&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; ]&nbsp; &nbsp; }");&nbsp;var tokens = JObject.Parse(jonsString)["someArray"].ToObject<List<Dictionary<string, string>>>().Where(p=>!p.Keys.Contains("item2"));&nbsp; &nbsp; &nbsp; &nbsp; foreach (var token in tokens)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;foreach(var item in token)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine(item.Key +":"+ item.Value);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; Console.ReadLine();输出:item1:5
随时随地看视频慕课网APP
我要回答