Home > Blockchain >  How to iterate through nested dynamic JSON file in Flutter
How to iterate through nested dynamic JSON file in Flutter

Time:12-04

So I have two JSON files with different fields.

{
  "password": { "length": 5, "reset": true},
}
"dataSettings": {
    "enabled": true,
    "algorithm": { "djikstra": true },
    "country": { "states": {"USA": true, "Romania": false}}
}

I want to be able to use the same code to be able to print out all the nested fields and its values in the JSON.

I tried using a [JSON to Dart converter package](https://javiercbk.github.io/json_to_dart/.

However, it seems like using this would make it so I would have to hardcode all the values, since I would retrieve it by doing

item.dataSettings.country.states.USA

which is a hardcoded method of doing it. Instead I want a way to loop through all the nested values and print it out without having to write it out myself.

CodePudding user response:

You can use ´dart:convert´ to convert the JSON string into an object of type Map<String, dynamic>:

import 'dart:convert';

final jsonData = "{'someKey' : 'someValue'}";
final parsedJson = jsonDecode(jsonData);

You can then iterate over this dict like any other:

parsedJson.forEach((key, value) {

  // ... Do something with the key and value

));

For your use case of listing all keys and values, a recursive implementation might be most easy to implement:

void printMapContent(Map<String, dynamic> map) {
   parsedJson.forEach((key, value) {
       print("Key: $key");  
       if (value is String) {
           print("Value: $value");
       } else if (value is Map<String, dynamic>) {
           // Recursive call
           printMapContent(value);
       }
   )); 
}

But be aware that this type of recursive JSON parsing is generally not recommendable, because it is very unstructured and prone to errors. You should know what your data structure coming from the backend looks like and parse this data into well-structured objects. There you can also perform input validation and verify the data is reasonable.

You can read up on the topic of "JSON parsing in dart", e.g. in this blog article.

  • Related