[英]How to convert JSON to YAML in javascript
我想将 json 字符串转换为 javascript 格式的 yaml 格式。我从过去两天开始尝试使用 Google 并没有找到任何解决方案或库。 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 中转换为它。
如果有人仍然想将 JSON 转换为 YAML,您可以使用这个 JavaScript 库: https : //www.npmjs.com/package/json2yaml
您可以使用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
YAML是JSON的超集。 由于任何有效的JSON也是有效的YAML,因此您无需转换任何内容。
我试图将答案打包到 bash 脚本中。
#!/bin/bash
#convert-json-to-yaml.sh
if [[ "$1" == "" ]]; then
echo "You must provide a json file in argument i.e. ./convert-json-to-yaml.sh your_file.json"
exit 1
fi
jsonFile=$1
yamlFile="$1.yaml"
if [[ "$2" != "" ]]; then
yamlFile=$2
fi
python -c 'import sys, yaml, json; yaml.safe_dump(json.load(sys.stdin), sys.stdout, default_flow_style=False)' < ${jsonFile} > ${yamlFile}
下面是如何做到这一点:) import * as YAML from 'yaml'; 常量 YAMLfile = YAML.stringify(JSONFILE);
如果你想创建一个 YAML 文件,你可以使用 de FS。 从'fs'导入*作为fs; fs.writeFileSync('./fileName.yaml', YAMLfile);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.