Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

toMap #147

Open
mnts opened this issue May 31, 2023 · 2 comments
Open

toMap #147

mnts opened this issue May 31, 2023 · 2 comments

Comments

@mnts
Copy link

mnts commented May 31, 2023

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

@clragon
Copy link

clragon commented Dec 1, 2023

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
Copy link

hndrbrm commented Jul 4, 2024

I use this ugly hack:

final jsonMap = jsonDecode(jsonEncode(yamlMap));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants