使用 javascript 将 yaml 转换为 json

2022-01-14 00:00:00 json yaml javascript

我得到了这个 yaml 文件:

I got this yaml file:

description:
  is_a: AnnotationProperty
  labelEN: description
  labelPT: descrição

relevance:
  is_a: AnnotationProperty
  domain: Indicator
  labelEN: relevance
  labelPT: relevância

title:
  is_a: AnnotationProperty
  labelPT: título
  labelEN: title
  range: Literal

我需要将其转换为 json,所以我可以得到这样的东西:

and I need to convert it to json, so I can get something like this:

{
    "description": {
        "is_a": "AnnotationProperty",
        "labelEN": "description",
        "labelPT": "descrição"
    },
    "relevance": {
        "is_a": "AnnotationProperty",
        "domain": "Indicator",
        "labelEN": "relevance",
        "labelPT": "relevância"
    },
    "title": {
        "is_a": "AnnotationProperty",
        "labelPT": "título",
        "labelEN": "title",
        "range": "Literal"
    }
}

并将其保存在 js 变量中...

and save it in a js variable...

那么,我该怎么做呢?

您好,请查看以下链接以获取 YAML 到 JSON 转换器https://www.yamlonline.com/

Hey, please check link below for YAML to JSON converter https://www.yamlonline.com/

推荐答案

你可以通过在 node.js 上运行一个简单的 javascript 脚本来解决这个问题.

You can solve that with a simple javascript script running on node.

  1. 安装 node.js
  2. 安装 js-yaml 包:npm install js-yaml -g

然后将此脚本保存到文件中,并使用 node.js 运行它:

Then save this script into a file, and run it with node.js:

var inputfile = 'input.yml',
    outputfile = 'output.json',
    yaml = require('js-yaml'),
    fs = require('fs'),
    obj = yaml.load(fs.readFileSync(inputfile, {encoding: 'utf-8'}));
// this code if you want to save
fs.writeFileSync(outputfile, JSON.stringify(obj, null, 2));

相关文章