Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@graphicbeacon graphicbeacon commented Feb 7, 2021

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