Home > Blockchain >  Dynamic loading of JSON file, and all of its contents with C#
Dynamic loading of JSON file, and all of its contents with C#

Time:09-22

Recently I've gotten into JSON parsing, and I was wondering, is it at all possible to completely dynamically load all of the contents within a JSON file? And by dynamically load, I mean, load all values of a JSON file without knowing any keys, meaning I cannot do the following code:

string contents = File.ReadAllText("SomeJsonFile.txt");
JObject obj = JObject.Parse(contents);
var value = obj["SomeKey"];

The reason I cannot do the code above, is because that would require the application to know the key ahead of time.

My goal is to be able to load any JSON file, and retrieve all values from said JSON file. I want to be able to load nested values, along with root values, all without knowing the keys. Is there a way for me to do this? If you need any more information, please don't hesitate to ask.

The way I want to use this data is to first, bind a textbox to a string version of each key. Then I will dynamically add the TextBoxes to a FlowLayoutPanel, I also want the user to be able to change this data, and the JSON to change with it.

Please help.

CodePudding user response:

If you don't know what the keys you are going to have you can use JArray from Json.NET to dynamically access the class.

See example instantiation and usage in the answer here:

How to access elements of a JArray (or iterate over them)

CodePudding user response:

Assuming the JSON is an object and not an array, you could deserialize the json string to a IDictionary<string, object> using Json.NET

string myJsonString = File.ReadAllText("SomeJsonFile.txt");
var dataObj = JsonConvert.DeserializeObject<IDictionary<string, object>>(myJsonString);

var topLevelKeys = dataObj.Keys;

Your original question already shows you've successfully parsed a JSON string into a C# object, without knowing the keys.

It appears your actual question is on how to flatten the JObject into some kind of enumerable set of key/value pairs. For that, I refer you to the answers on this thread: Generically Flatten Json using c#

Answer 2 IMO looks a lot cleaner:

string contents = File.ReadAllText("SomeJsonFile.txt");
var schemaObject = JObject.Parse(contents);
var values = schemaObject
    .SelectTokens("$..*")
    .Where(t => !t.HasValues)
    .ToDictionary(t => t.Path, t => t.ToString());
  • Related