如何在 Dart 中将映射写入 YAML 文件

Bir*_*ani 6 yaml dart dart-io

我在 Dart 中有一张键值对的映射。我想将其转换YAML并写入文件。

我尝试使用YAMLdart 库中的包,但它只提供YAML从文件加载数据的方法。没有提及如何将其写回文件YAML

这是一个例子:

void main() {
  var map = {
    "name": "abc",
    "type": "unknown",
    "internal":{
      "name": "xyz"
    }
  };
  print(map);
}
Run Code Online (Sandbox Code Playgroud)

预期输出: example.yaml

name: abc
type: unknown
internal:
  name: xyz
Run Code Online (Sandbox Code Playgroud)

如何将 dart 映射转换为 YAML 并将其写入文件?

小智 6

虽然回复有点晚了,但对于其他看到这个问题的人来说,我已经写了这门课。它可能并不完美,但它适用于我正在做的事情,而且我还没有发现它有什么问题。编写测试后最终可能会将其打包。

class YamlWriter {
  /// The amount of spaces for each level.
  final int spaces;

  /// Initialize the writer with the amount of [spaces] per level.
  YamlWriter({
    this.spaces = 2,
  });

  /// Write a dart structure to a YAML string. [yaml] should be a [Map] or [List].
  String write(dynamic yaml) {
    return _writeInternal(yaml).trim();
  }

  /// Write a dart structure to a YAML string. [yaml] should be a [Map] or [List].
  String _writeInternal(dynamic yaml, { int indent = 0 }) {
    String str = '';

    if (yaml is List) {
      str += _writeList(yaml, indent: indent);
    } else if (yaml is Map) {
      str += _writeMap(yaml, indent: indent);
    } else if (yaml is String) {
      str += "\"${yaml.replaceAll("\"", "\\\"")}\"";
    } else {
      str += yaml.toString();
    }


    return str;
  }

  /// Write a list to a YAML string.
  /// Pass the list in as [yaml] and indent it to the [indent] level.
  String _writeList(List yaml, { int indent = 0 }) {
    String str = '\n';

    for (var item in yaml) {
      str += "${_indent(indent)}- ${_writeInternal(item, indent: indent + 1)}\n";
    }

    return str;
  }

  /// Write a map to a YAML string.
  /// Pass the map in as [yaml] and indent it to the [indent] level.
  String _writeMap(Map yaml, { int indent = 0 }) {
    String str = '\n';

    for (var key in yaml.keys) {
      var value = yaml[key];
      str += "${_indent(indent)}${key.toString()}: ${_writeInternal(value, indent: indent + 1)}\n";
    }

    return str;
  }

  /// Create an indented string for the level with the spaces config.
  /// [indent] is the level of indent whereas [spaces] is the
  /// amount of spaces that the string should be indented by.
  String _indent(int indent) {
    return ''.padLeft(indent * spaces, ' ');
  }
}
Run Code Online (Sandbox Code Playgroud)

用法:

final writer = YamlWriter();
String yaml = writer.write({
  'string': 'Foo',
  'int': 1,
  'double': 3.14,
  'boolean': true,
  'list': [
    'Item One',
    'Item Two',
    true,
    'Item Four',
  ],
  'map': {
    'foo': 'bar',
    'list': ['Foo', 'Bar'],
  },
});

File file = File('/path/to/file.yaml');
file.createSync();
file.writeAsStringSync(yaml);
Run Code Online (Sandbox Code Playgroud)

输出:

string: "Foo"
int: 1
double: 3.14
boolean: true
list: 
  - "Item One"
  - "Item Two"
  - true
  - "Item Four"

map: 
  foo: "bar"
  list: 
    - "Foo"
    - "Bar"
Run Code Online (Sandbox Code Playgroud)


Kev*_*ore 2

package:yaml没有YAML编写功能。您可能需要寻找另一个可以执行此操作的软件包 \xe2\x80\x93\xc2\xa0 或编写您自己的软件包。

\n\n

作为权宜之计,请记住 JSON 是有效的 YAML,因此您始终可以将 JSON 写入文件.yaml,并且它应该适用于任何 YAML 解析器。

\n