skip to Main Content

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*]

2

Answers


  1. 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:

    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();
    
    Login or Signup to reply.
  2. 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();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search