【问题标题】:How do I get a list of all properties in a JSON document?如何获取 JSON 文档中所有属性的列表?
【发布时间】:2019-02-07 05:31:45
【问题描述】:

我有一个动态 JSON 文档,但为了这个问题,假设它类似于以下内容:

{ "name": "Jungle Gym", "age": 25, "favorite_color": "#ffa500", "gender": "male", "location": { "city": "Seattle", "state": "WA", "citystate": "Seattle, WA" }, "pets": [ { "type": "dog", "name": "Foo", "food": [ "chicken", "beef", "fish" ] }, { "type": "cat", "name": "Bar" } ] }

如何获取文档中所有属性名称的列表?我可以获得顶级属性名称(“name”、“age”、“favorite_color”、“gender”、“location”、“pets”),但我需要将所有属性名称归结为“location.state”或“ pets.food”,如果属性/对象存在,甚至更深。 我开始使用以下内容:

var model = JsonConvert.DeserializeObject<JObject>(json);

foreach (JProperty property in model.Properties())
{
    if (property.Value.Type == JTokenType.Object)
    {
        foreach (var tmp in property.Children())
        {
            Console.WriteLine(tmp.SelectToken().);
        }
    }
}

但似乎无法导航到超出顶层的对象以获取下一级属性(例如位置属性)。理想情况下,我希望派生属性名称列表包含属性的完整路径,例如location.citylocation.state 等,而不仅仅是属性名称,例如city, state.

如何获取 JSON 文档中所有可能具有不同嵌套级别的属性的列表?

【问题讨论】:

标签: recursion json.net


【解决方案1】:

为了获取 Json 字符串中的所有键(所有级别),您可以使用 DescendantsPath 属性来获取详细信息。

var data = JObject.Parse(jsonString);
var result = data.Descendants()
            .OfType<JProperty>()
            .Select(f=>Regex.Replace(f.Path,@"\[[0-9]\]",string.Empty))
            .Distinct();

请注意,Regex 用于替换所有可能因宠物列表而产生的索引。

输出,

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-07
    • 2011-06-04
    • 2021-10-31
    • 2019-01-12
    • 2020-11-03
    • 1970-01-01
    相关资源
    最近更新 更多