如何用Newtonsoft.Json的JToken.SelectTokens匹配Ethernet*模式的PORT子对象?
解决方案:匹配PORT节点下Ethernet开头的子对象
你的JSONPath语句失效的核心原因是:@在当前上下文指向的是子对象的值(比如{"id":0}),而非子对象的键名(比如Ethernet0),导致正则匹配的目标错误。
方案1:修正JSONPath表达式
Newtonsoft.Json支持通过$keys获取当前对象的键名,结合过滤条件实现匹配。正确的JSONPath语句如下:
$.PORT.*[?($keys =~ /Ethernet\d+/)]
$.PORT.*:遍历PORT节点下的所有子对象[?($keys =~ /Ethernet\d+/)]:筛选出键名符合Ethernet\d+正则规则的对象
对应的C#代码示例:
using Newtonsoft.Json.Linq; using System; var json = @"{ ""PORT"" : { ""Ethernet0"": { ""id"": 0 }, ""Ethernet1"": { ""id"" : 1 }, ""Foo"": { ""id"": 2 } } }"; JToken root = JToken.Parse(json); var matchedTokens = root.SelectTokens("$.PORT.*[?($keys =~ /Ethernet\\d+/)]"); foreach (var token in matchedTokens) { Console.WriteLine(token.ToString()); }
方案2:手动遍历筛选(更直观)
若对JSONPath语法不熟悉,可直接遍历PORT节点的属性,通过正则匹配键名筛选:
using Newtonsoft.Json.Linq; using System; using System.Text.RegularExpressions; using System.Linq; var json = @"{ ""PORT"" : { ""Ethernet0"": { ""id"": 0 }, ""Ethernet1"": { ""id"" : 1 }, ""Foo"": { ""id"": 2 } } }"; JObject portObject = JToken.Parse(json)["PORT"] as JObject; var ethernetRegex = new Regex(@"Ethernet\d+"); var matchedObjects = portObject.Properties() .Where(prop => ethernetRegex.IsMatch(prop.Name)) .Select(prop => prop.Value); foreach (var obj in matchedObjects) { Console.WriteLine(obj.ToString()); }
内容的提问来源于stack exchange,提问作者Prasad Korhale
相关产品推荐
相关产品推荐

