Home > OS >  Take the data from json string and pass children nodes to the first level with navigation path
Take the data from json string and pass children nodes to the first level with navigation path

Time:11-29

Hello I have this example json string:

{
   "property1":"value1",
   "property2":"value2",
   "anotherObject":{
      "property1":"anothervalue1",
      "property2":"anothervalue2",
      "anotherOfAnother":{
         "property1":"value1"
      }
   }
}

I need to get all others json objects inside and pass then to first level, preserving navigation path. So example Json becomes:

{
   "property1":"value1",
   "property2":"value2",
   "anotherObject.property1":"anothervalue1",
   "anotherObject.property2":"anothervalue2",
   "anotherObject.anotherOfAnother.Property1":"value1"
}

How can I do it? I'm on .Net 6 Thanks in advance

I'm stuck, I haven't tried nothing yet. I'm looking for ideas on efficient ways to reach the goal, using JObject or JsonConvert.

CodePudding user response:

you can use Path property

   var jsonObject = JObject.Parse(json);

    var result = jsonObject.Descendants()
        .Where(t => !t.HasValues)
        .Select(t => "\""   t.Path   "\""   " : "   "\""   t.ToString()   "\",")
        .ToArray();

    //cut off the last ","
    result[result.Length - 1] = result[result.Length - 1]
                                  .Substring(0, result[result.Length - 1].Length - 1);

    json = "{\n"   string.Join("\n", result)   "\n}";

CodePudding user response:

There doesn't seem to be a way around this being an O(n) problem. I would use Newtonsoft's JObject.Parse(string) function to get a tree of enumerables you can iterate over the .Children() of in a recursive loop.

Each element as a JToken has a property Path which is the dot-notation key you're looking for in your new JSON object. To get O(n) performance you can construct a new document as you go, but it might be easier to just use the recursion to construct a flat list of key-value pairs and simply build the document post-iteration from the new list (which gives you O(n) x2).

Due to the nesting nature of json, mutating the existing document, while possible is very likely more work than it's worth.

You'll have to fiddle with the differences between the root JObject and each nested token, and you'll have to figure out what you want to do about arrays, but that should get you most of the way there.

  • Related