Search code examples
c#jsonforeachchildren

Looping through JObject to get Property Name


As its breifly described in the title im trying to loop through a JObject to get all names of the keys inside, however as you can see this is specified under the sub-key "Bayonet".While this works fine, i need a more general approach as the "Bayonet" subkey wont always be present. Here are some of my tries:

Working solution but ungeneralized:

foreach (JProperty condition in SkinData[Skin]["Bayonet"])
{
     conditionlines.Add(condition.Name);
}

Failing with Can't convert JObject to JProperty Error:

foreach (JProperty condition in SkinData[Skin].First)
{
    conditionlines.Add(condition.Name);
}

Failing with No Name String Error:

foreach (JProperty condition in SkinData[Skin][0])
{
    conditionlines.Add(condition.Name);
}

JSON:

{  
   "Scorched":{  
      "Bayonet":{  
         "FN":"51",
         "MW":"32",
         "FT":"25",
         "WW":"26",
         "BS":"26"
      },
      "Bowie Knife":{  
         "MW":"25",
         "FT":"20",
         "WW":"21",
         "FN":"41",
         "BS":"20"
      },
      "Butterfly Knife":{  
         "FN":"50",
         "MW":"36",
         "FT":"29",
         "WW":"28",
         "BS":"29"
      },
      "Falchion Knife":{  
         "FN":"31",
         "MW":"20",
         "FT":"17",
         "WW":"17",
         "BS":"17"
      },
      "Flip Knife":{  
         "FN":"0",
         "MW":"24",
         "FT":"20",
         "WW":"20",
         "BS":"20"
      },
      "Gut Knife":{  
         "FN":"0",
         "MW":"19",
         "FT":"17",
         "WW":"18",
         "BS":"17"
      },
      "Huntsman Knife":{  
         "FN":"48",
         "MW":"27",
         "FT":"21",
         "WW":"21",
         "BS":"20"
      },
      "Karambit":{  
         "FN":"87",
         "MW":"55",
         "FT":"43",
         "WW":"42",
         "BS":"41"
      },
      "M9 Bayonet":{  
         "FN":"54",
         "MW":"38",
         "FT":"30",
         "WW":"30",
         "BS":"30"
      },
      "Shadow Daggers":{  
         "FN":"29",
         "MW":"20",
         "FT":"17",
         "WW":"17",
         "BS":"17"
      }
   }
}

Solution

  • You could do:

    foreach (var condition in ((JContainer)SkinData[Skin]).Descendants().OfType<JObject>().Take(1).Properties())
    {
         conditionlines.Add(condition.Name);
    }       
    

    This finds the first descendant (if any) of the token specified by Skin that is of type JObject, then loops through its properties.

    Sample fiddle.