Skip to content

Instantly share code, notes, and snippets.

@graphicbeacon
Created February 7, 2021 22:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save graphicbeacon/4d39701935b200d88d32193e7c453be7 to your computer and use it in GitHub Desktop.
Save graphicbeacon/4d39701935b200d88d32193e7c453be7 to your computer and use it in GitHub Desktop.
Convert map object to yaml in Dart
void main() {
final json = {
'name': 'package_name',
'version': '1.0.0',
'dependencies': {
'dep1': '^1.0.0',
'dep2': '^1.5.0',
'dep3': {
'git': 'https://github.com/graphicbeacon',
'home': {
'work': 'play'
}
}
},
'dev_dependencies': {
'dep1': '2.0.0',
'dep3': {
'git': 'https://github.com/graphicbeacon',
'home': {
'work': 'play'
}
}
}
};
final buffer = StringBuffer();
final entriesList = json.entries.toList();
mapToYaml(buffer, entriesList, 0);
print(buffer.toString());
}
mapToYaml(StringBuffer buffer, List<MapEntry> entries, int spacing) {
for (final entry in entries) {
final spaces = ' ' * spacing;
if (entry.value is String) {
buffer.writeln('$spaces${entry.key}: ${entry.value}');
} else if (entry.value is Map) {
buffer.writeln('$spaces${entry.key}:');
// Recursive
mapToYaml(buffer, entry.value.entries.toList(), spacing + 2);
}
}
}
@graphicbeacon
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment