How to load Yaml file to the Map in Dart? How to load Yaml file to the Map in Dart? dart dart

How to load Yaml file to the Map in Dart?


Look at the source of loadYaml in yaml.dart. If you use eclipse or the DartEditor you can also just hover your mouse over loadYaml to get a description.It says there that if the function returns a map it's a YamlMap, not a normal Dart map. It may also return something else e.g. String, num, List.Why don't you just do a print(map) or print(map.runtimeType)?


I'd imagine that to be watertight, the code below needs a little more work, but this is working for my basic purposes where I transitioned from JSON to YAML and wanted to retain the remainder of my codebase almost unchanged.

import 'package:yaml/yaml.dart';extension YamlMapConverter on YamlMap {  dynamic _convertNode(dynamic v) {    if (v is YamlMap) {      return (v as YamlMap).toMap();    }    else if (v is YamlList) {      var list = <dynamic>[];      v.forEach((e) { list.add(_convertNode(e)); });      return list;    }    else {      return v;    }  }  Map<String, dynamic> toMap() {    var map = <String, dynamic>{};    this.nodes.forEach((k, v) {      map[(k as YamlScalar).value.toString()] = _convertNode(v.value);    });    return map;  }}...var yamlData = loadYaml(yaml);Map<String, dynamic> dartMap = yamlMap.toMap();...

To become watertight, it would need to handle exceptions better and also handle items like YAML tags. I haven't needed these so I haven't developed it further.

Code based on Dart-YAML version ^3.1.0