英文:
How to get a value from JSON object with approximate key
问题
我想从rackD1到rackD1000中心为south的键值使用LINQ提取。是否可以像JsonContent["serviceMap"][rackD1*]这样提取键值?
英文:
I have below JSON file under service map, The Key values are not fixed
{
"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"
}
}
}
I want to extract the key values from rackD1 to rackD1000 whose center is south using linq.
is it possible to extract the key value like JsonContent["serviceMap"][rackD1*]
答案1
得分: 1
只需将其反序列化为正确的类结构并在结果上使用 LINQ。
public class Root
{
// 使用字典表示动态属性名称
public Dictionary<string, ServiceMap> ServiceMap { get; set; }
}
public class ServiceMap
{
public string Env { get; set; } // 如果不需要可以排除
public string Center { get; set; }
}
然后筛选结果:
```csharp
var root = ... ; // 反序列化的 root
var result = root.ServiceMap
.Where(kvp => kvp.Value.Center == "south") // 或 kvp.Value.Center.Equals("south", StringComparison.InvariantCultureIgnoreCase) 以进行不区分大小写的比较
.Select(kvp => kvp.Key) // 键,如 "rackD1",...
.ToList();
<details>
<summary>英文:</summary>
Just deserialize it to proper class structure and use LINQ on the results.
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; }
}
And filter results:
```csharp
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();
答案2
得分: 1
你不需要任何类来获取键列表:
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();
英文:
you dont need any classes to get list of keys
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();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论