You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中如何遍历嵌套的动态JSON文件

遍历嵌套JSON并打印所有字段及其值的通用方法

示例JSON结构

第一个JSON:

{
  "password": { "length": 5, "reset": true }
}

第二个JSON:

{
  "dataSettings": {
    "enabled": true,
    "algorithm": { "djikstra": true },
    "country": { "states": {"USA": true, "Romania": false} }
  }
}

通用解决方案(Dart)

你可以用递归遍历的方式实现,无需硬编码任何字段路径,代码能自动适配所有嵌套结构:

void printNestedJson(dynamic json, [String currentPath = '']) {
  if (json is Map<String, dynamic>) {
    // 遍历Map的每个键值对
    json.forEach((key, value) {
      String newPath = currentPath.isEmpty ? key : '$currentPath.$key';
      printNestedJson(value, newPath);
    });
  } else if (json is List) {
    // 处理数组类型(适配含数组的JSON结构)
    for (int i = 0; i < json.length; i++) {
      String newPath = '$currentPath[$i]';
      printNestedJson(json[i], newPath);
    }
  } else {
    // 基本类型,直接打印路径和对应值
    print('$currentPath: $json');
  }
}

使用示例

void main() {
  // 测试第一个JSON
  final json1 = {
    "password": { "length": 5, "reset": true }
  };
  print('=== 第一个JSON遍历结果 ===');
  printNestedJson(json1);

  // 测试第二个JSON
  final json2 = {
    "dataSettings": {
      "enabled": true,
      "algorithm": { "djikstra": true },
      "country": { "states": {"USA": true, "Romania": false} }
    }
  };
  print('\n=== 第二个JSON遍历结果 ===');
  printNestedJson(json2);
}

输出结果

=== 第一个JSON遍历结果 ===
password.length: 5
password.reset: true

=== 第二个JSON遍历结果 ===
dataSettings.enabled: true
dataSettings.algorithm.djikstra: true
dataSettings.country.states.USA: true
dataSettings.country.states.Romania: false

这个方案的核心是通过递归自动识别JSON的类型(Map/List/基本类型),逐层遍历并拼接字段路径,最终输出所有嵌套字段和对应值,完全不需要根据JSON结构硬编码字段访问路径。

内容的提问来源于stack exchange,提问作者osstackerf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 14:55:22