Home > front end >  How to write every Json property into a List without its content
How to write every Json property into a List without its content

Time:10-27

I have a .Json file like this:

{
   "Main":{
      "Funktion":{
         "Sub1":"",
         "Sub2":{
            "something1":"",
            "something2":"",
            "something3":""
         },
         "Sub3":{
            "something4":""
         },
         "Sub4":{
            "something5":""
         },
         "Sub5":{
            "something6":""
         }
      }
   }
}

Now i want to write every "SubX" into a List or Array but without the text within each Sub.

So it will look like this

OUTPUT:

Printed List:
"Sub1"
"Sub2"
"Sub3"
"Sub4"
"Sub5"

I´ve already made it with converting to a String and via String handle. Now i wonder if there is a more elegant solution for this problem.

CodePudding user response:

One way to retrieve only the names of the Funktion sub-nodes is the following:

JObject.Parse(json)["Main"]["Funktion"].Children().Select(x => ((JProperty)x).Name)
  • With JObject.Parse we same parse the json
  • With ["Main"]["Funktion"] we travers through the nodes
  • With .Children() we ask for the sub-nodes (JTokens)
  • With .Select we cast the JToken to JProperty to be able to get the Name property

I want to emphasize that this approach is error-prone. It highly relies on actual structure. In order to make it more robust please consider to use TryGetValue instead of index operator.

  • Related