gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 03:37:11 26 4
gpt4 key购买 nike

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

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

这是一个例子:

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

预期输出:example.yaml

name: abc
type: unknown
internal:
name: xyz

如何将dart map转YAML并写入文件?

最佳答案

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

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, ' ');
}
}

用法:

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);

输出:

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

map:
foo: "bar"
list:
- "Foo"
- "Bar"

关于dart - 如何在 Dart 中将映射写入 YAML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60051282/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com