Created
February 7, 2021 22:29
-
-
Save graphicbeacon/4d39701935b200d88d32193e7c453be7 to your computer and use it in GitHub Desktop.
Convert map object to yaml in Dart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Run on DartPad https://dartpad.dev/4d39701935b200d88d32193e7c453be7