Click here to Skip to main content
15,881,898 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi.
C# Issue a head:
I have an anonymous Json.
I need to disassemble only the internal objects (those surrounded by curly braces) and flatten them.
This should be done in a generic way so that no matter what the depth of the object (a child can contain an infinity of children and grandchildren) - all objects that are in curly brackets (and only they) will be flattened out into the Dictionary.
Please look at the following example:
{
  "A": "xxxxx",
  "Groups": [
    "xxxxx",
    "xxxxx",
    "xxxxx"
  ],
  "B": "xxxxx",
  "C": "xxxxx",
  "D": "xxxxx",
  "E": "xxxxx",
  "F": "xxxxx",
  "G": null,
  "H": "xxxxx",
  "I": {
    "H": "xxxxx"
  },
  "J": {
    "K": "xxxxx",
    "L": "xxxxx",
    "M": "xxxxx",
    "N": "xxxxx",
    "O": {
      "P": "xxxxx",
      "Q": "xxxxx",
      "R": "xxxxx",
      "T": "xxxxx",
      "U": {
        "V": "xxxxx"
      }
    },
    "W": "xxxxx"
  },
  "X": {
    "Y": "xxxxx",
    "Z": "xxxxx"
  },
  "AA": {
    "AB": "xxxxx",
    "AC": "xxxxx"
  },
  "AD": {
    "AE": "xxxxx",
    "AF": "xxxxx"
  }
}

I need the result to be:
"H": "xxxxx"
"K": "xxxxx",
"L": "xxxxx",
"M": "xxxxx",
"N": "xxxxx",
"P": "xxxxx",
"Q": "xxxxx",
"R": "xxxxx",
"T": "xxxxx",
"V": "xxxxx"
"W": "xxxxx"
"Y": "xxxxx",
"Z": "xxxxx"
"AB": "xxxxx",
"AC": "xxxxx"
"AE": "xxxxx",
"AF": "xxxxx"


Please note also the second object in Json ('Groups'): it should not be part of the flattened list.

What I have tried:

I tried using SelectTokens like this:
C#
var allLevels = schemaObject.SelectTokens("$..*").Where(t => !t.HasValues).ToDictionary(t => t.Path, t => t.ToString());

but it also breaks down the most external parameters (for example: "A") and the "Groups" into three objects (when in fact I do not want it at all).
Posted
Updated 22-Jul-21 22:54pm
v2

1 solution

It would be much simpler and faster if you parsed the entire block of json data into known entities (in other words, you have to define them so you can correctly parse the json data), and then used Linq to "flatten" your data.

It looks like you want the most last child(ren) of a given chain, but only for "groups" that have children at all. I'm not gonna sit here and try to figure it out for you, but that's essentially what you want to do.

Alternatively (and I would never allow this in our products because I like strong typing), you can try this:

Using JSON.NET for dynamic JSON parsing - Rick Strahl's Web Log[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900