如何在javascript中将JSON转换为YAML

时间:2016-08-05 05:46:29

标签: javascript json yaml

我想在javascript中将json字符串转换为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中转换为它。

5 个答案:

答案 0 :(得分:5)

您可以使用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

答案 1 :(得分:3)

如果有人仍想将JSON转换为YAML,您可以使用此JavaScript库: https://www.npmjs.com/package/json2yaml

答案 2 :(得分:2)

使用'js-yaml'npm包!这是yaml.org官方认可的那个。 (如果你想要更加确定&&&&这篇文章已经过时了,请自己检查一下yaml.org以查看它推荐的软件包。)我最初使用'json2yaml'代替并在转换json时获得了奇怪的解析行为(如字符串)到yaml。

答案 3 :(得分:0)

YAML是JSON的超集。由于任何有效的JSON也是有效的YAML,因此您无需转换任何内容。

答案 4 :(得分:0)

我试图将答案打包到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}