I know the Yaml library from Pub, which can load and parse Yaml string through loadYaml() function. But I don't know, how to load content of the Yaml file as the parameter of this function.
My Code (isn't working):
data.yaml
name1: thing1
name2: thing2
process.dart
import 'dart:html';
import 'package:yaml/yaml.dart';
main(){
String path = 'data.yaml';
return HttpRequest.getString(path)
.then((String yamlString){
YamlMap map = loadYaml(yamlString);
String name = map['name1'];
print(name);
});
}
I'd imagine that to be watertight, the code below needs a little more work, but this is working for my basic purposes where I transitioned from JSON to YAML and wanted to retain the remainder of my codebase almost unchanged.
import 'package:yaml/yaml.dart';
extension YamlMapConverter on YamlMap {
dynamic _convertNode(dynamic v) {
if (v is YamlMap) {
return (v as YamlMap).toMap();
}
else if (v is YamlList) {
var list = <dynamic>[];
v.forEach((e) { list.add(_convertNode(e)); });
return list;
}
else {
return v;
}
}
Map<String, dynamic> toMap() {
var map = <String, dynamic>{};
this.nodes.forEach((k, v) {
map[(k as YamlScalar).value.toString()] = _convertNode(v.value);
});
return map;
}
}
...
var yamlData = loadYaml(yaml);
Map<String, dynamic> dartMap = yamlMap.toMap();
...
To become watertight, it would need to handle exceptions better and also handle items like YAML tags. I haven't needed these so I haven't developed it further.
Code based on Dart-YAML version ^3.1.0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With