gpt4 book ai didi

javascript - 如何在 JavaScript 中将 JSON 转换为 YAML

转载 作者:数据小太阳 更新时间:2023-10-29 05:11:52 26 4
gpt4 key购买 nike

我想在 javascript 中将 json 字符串转换为 yaml 格式。我在过去两天尝试使用谷歌搜索,但没有找到任何解决方案或库。有适用于 java 但不适用于 javascript 的答案。

假设我有这样的 json 字符串:

{
"json": [
"fat and rigid"
],
"yaml": [
"skinny and flexible"
],
"object": {
"array": [
{
"null_value": null
},
{
"boolean": true
},
{
"integer": 1
}
]
}
}

转换为 yaml:

json:
- fat and rigid
yaml:
- skinny and flexible
object:
array:
- null_value:
- boolean: true
- integer: 1

有在线转换器http://www.json2yaml.com/ , 但如何在 javascript 中转换为它。

最佳答案

您可以使用 yaml NPM 包。

const YAML = require('yaml');

const jsonObject = {
version: "1.0.0",
dependencies: {
yaml: "^1.10.0"
},
package: {
exclude: [ ".idea/**", ".gitignore" ]
}
}

const doc = new YAML.Document();
doc.contents = jsonObject;

console.log(doc.toString());

输出

version: 1.0.0
dependencies:
yaml: ^1.10.0
package:
exclude:
- .idea/**
- .gitignore

关于javascript - 如何在 JavaScript 中将 JSON 转换为 YAML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38781929/

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