Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load Yaml file to the Map in Dart?

Tags:

file

yaml

dart

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);
    });    
}
like image 332
aleskva Avatar asked Oct 20 '25 04:10

aleskva


1 Answers

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

like image 115
user1738833 Avatar answered Oct 23 '25 07:10

user1738833