如何使用近似键从JSON对象中获取值

sg2wtvxw  于 2023-02-10  发布在  其他
关注(0)|答案(2)|浏览(171)

我有下面的JSON文件下的服务Map,键值不固定

{
"ServiceMap": {
    "rackAC1": {
        "Env": "Public",
        "Center": "north"
    },
    "rackD1": {
        "Env": "Public",
        "Center": "south"
    },
    "rackD2": {
        "Env": "Public",
        "Center": "North-south"
    },
    "rackD3": {
        "Env": "Public",
        "Center": "south"
    },
    ...,
    "rackD1000": {
        "Env": "Public",
        "Center": "south"
    },
    "rackBO": {
        "Env": "Public",
        "Center": "East"
    },
    "rackB1": {
        "Env": "Public",
        "Center": "West"
    }
}

}我想使用linq提取从rackD1到rackD1000的键值,其中心在南方。是否可以像JsonContent[“serviceMap”][rackD1*]那样提取键值

bweufnob

bweufnob1#

你不需要任何类来获取键列表

List<string> keys = ((JObject)JObject.Parse(json)["ServiceMap"]).Properties()
    .Where(p => p.Name.Contains("rackD") 
                  && ((string)p.Value["Center"]).ToLower() == "south")
    .Select(p => p.Name)
    .ToList();
c3frrgcw

c3frrgcw2#

只需将其反序列化为适当的类结构并对结果使用LINQ即可。

public class Root
{
    // use dictionary to represent dynamic property names
    public Dictionary<string, ServiceMap> ServiceMap { get; set; } 
}

public class ServiceMap
{
    public string Env { get; set; } // can be excluded if not needed
    public string Center { get; set; }
}

和过滤结果:

var root = ... ; // deserialized root
var result = root.ServiceMap
   .Where(kvp => kvp.Value.Center == "south") // or kvp.Value.Center.Equals("south", StringComparison.InvariantCultureIgnoreCase) for case-insensitive
   .Select(kvp => kvp.Key) // keys like "rackD1", ...
   .ToList();

相关问题