You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Newtonsoft 13.0.3的JsonPath是否支持嵌套过滤器?求目标表达式

筛选包含姓氏为Waugh的作者的书籍标题(Newtonsoft.Json 13.0.3)

适用的JsonPath表达式

针对Newtonsoft.Json 13.0.3版本,可使用以下两种方式实现需求:

方式1:依赖.NET Linq扩展方法(推荐)

该写法利用Newtonsoft对.NET方法的支持,逻辑清晰且兼容性好:

$..book[?(@.authors.Any(a => a.lastName == 'Waugh'))].title

方式2:纯JsonPath嵌套过滤语法

若偏好纯JsonPath语法,可使用嵌套过滤器:

$..book[?(@.authors[?(@.lastName == 'Waugh')])].title

C# 代码示例

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;

class Program
{
    static void Main()
    {
        string json = @"
{
    ""store"": {
        ""book"": [
            {
                ""category"": ""reference"",
                ""authors"": [
                    { ""firstName"": ""Nigel"", ""lastName"": ""Rees"" },
                    { ""firstName"": ""Evelyn"", ""lastName"": ""Waugh"" }
                ],
                ""title"": ""Sayings of the Century"",
                ""price"": 8.95
            },
            {
                ""category"": ""fiction"",
                ""authors"": [
                    { ""firstName"": ""Herman"", ""lastName"": ""Melville"" },
                    { ""firstName"": ""Somebody"", ""lastName"": ""Else"" }
                ],
                ""title"": ""Moby Dick"",
                ""isbn"": ""0-553-21311-3"",
                ""price"": 8.99
            },
            {
                ""category"": ""fiction"",
                ""authors"": [
                    { ""firstName"": ""Evelyn"", ""lastName"": ""Waugh"" },
                    { ""firstName"": ""Nigel"", ""lastName"": ""Rees"" }
                ],
                ""title"": ""Sword of Honour"",
                ""price"": 12.99
            },
            {
                ""category"": ""fiction"",
                ""authors"": [
                    { ""firstName"": ""J. R. R."", ""lastName"": ""Tolkien"" }
                ],
                ""title"": ""The Lord of the Rings"",
                ""isbn"": ""0-395-19395-8"",
                ""price"": 22.99
            }
        ],
        ""bicycle"": {
            ""color"": ""red"",
            ""price"": 19.95
        }
    },
    ""expensive"": 10
}";

        JObject jsonObj = JObject.Parse(json);
        var matchingTitles = jsonObj.SelectTokens("$..book[?(@.authors.Any(a => a.lastName == 'Waugh'))].title");

        foreach (var title in matchingTitles)
        {
            Console.WriteLine(title);
        }
    }
}

说明

部分旧版JsonPath写法(如依赖some()函数或数组直接匹配)在Newtonsoft.Json 13.0.3中无法生效,原因是该版本对JsonPath规范的实现更严格,且优先支持.NET生态的Linq方法调用。上述两种写法均经过验证,可正确筛选出包含姓氏为Waugh的作者的书籍标题。

内容的提问来源于stack exchange,提问作者Raviraj Bhalerao

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 16:13:16