dart-lang / yaml

A Dart YAML parser.
https://pub.dev/packages/yaml
MIT License
169 stars 58 forks source link

toMap #147

Open mnts opened 1 year ago

mnts commented 1 year ago

why there is no simple way described, just to convert this YamlDocument into ordinary Map type?

clragon commented 11 months ago

The documentation promises that in the future, YamlMap would just be a regular Map instead. However, this future does not seem to have resolved as of yet, which is incredibly inconvenient for using fromJson methods with the decoded Yaml.

from the loadYaml docs:

The return value is mostly normal Dart objects. However, since YAML mappings support some key types that the default Dart map implementation doesn't (NaN, lists, and maps), all maps in the returned document are YamlMaps. These have a few small behavioral differences from the default Map implementation; for details, see the YamlMap class.

In future versions, maps will instead be HashMaps with a custom equality operation.

For that reason, I have written a small method that undoes this mess:

/// Recreates all Maps and Lists recursively to ensure normal Dart types
dynamic yamlToDart(dynamic value) {
  if (value is Map) {
    List<MapEntry<String, dynamic>> entries = [];
    // we cannot directly use `entries` because `YamlMap` will return Nodes instead of values.
    for (final key in value.keys) {
      entries.add(MapEntry(key, yamlToDart(value[key])));
    }
    return Map.fromEntries(entries);
  } else if (value is List) {
    return List.from(value.map(yamlToDart));
  } else {
    return value;
  }
}

this is more of a hack than anything, but it should normalize your types.

hndrbrm commented 3 months ago

I use this ugly hack:

final jsonMap = jsonDecode(jsonEncode(yamlMap));