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

如何使用Json.Net结合JSONPath获取嵌套JSON的属性名?

Can Json.Net (Newtonsoft.Json) use JSONPath to get property names from nested JSON?

Short answer: No, Newtonsoft.Json's built-in JSONPath implementation doesn't support the ~ syntax (used in libraries like JSONPath-Plus) to retrieve property names directly.

For your specific example JSON:

{"fields": {"hum": 48.1, "temp": 24.4}}

If you need to get the property names hum and temp in .NET Core, here are two straightforward alternatives using Newtonsoft.Json:

1. Directly parse and traverse the JObject

This is the simplest and most efficient approach—no JSONPath required:

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

// Parse your JSON string
var jsonString = @"{""fields"": {""hum"": 48.1, ""temp"": 24.4}}";
var rootObject = JObject.Parse(jsonString);

// Access the "fields" object and get its property names
if (rootObject.TryGetValue("fields", out JToken fieldsToken) && fieldsToken is JObject fieldsObject)
{
    var propertyNames = fieldsObject.Properties().Select(p => p.Name);
    
    // Iterate over the names or use them as needed
    foreach (var name in propertyNames)
    {
        Console.WriteLine(name); // Outputs: hum, temp
    }
}

2. Why JSONPath ~ doesn't work with Newtonsoft.Json

Newtonsoft.Json's JSONPath implementation adheres to the original JSONPath specification by Stefan Goessner. The ~ operator is an extension added by libraries like JSONPath-Plus, which isn't part of the standard spec Newtonsoft follows. So there's no built-in way to use that syntax with Newtonsoft.Json.

If you really want to use a JSONPath-like approach with property name retrieval, you'd need to either:

  • Implement a custom JSONPath evaluator that adds support for ~
  • Use a third-party .NET library that supports extended JSONPath features (though most popular ones stick to the standard spec)

But for your use case, directly traversing the JObject is the most practical solution in .NET Core.

内容的提问来源于stack exchange,提问作者Georges Legros

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:31:15