简体   繁体   中英

How to iterate through nested dynamic JSON file in Flutter

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.

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", eg in this blog article .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM