Convert yaml to json [duplicate]

2020-07-10 08:11发布

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

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"
    }
}

and save it in a js variable...

So, how can I do this?

2条回答
叼着烟拽天下
2楼-- · 2020-07-10 08:38

There is—unfortunately—nothing in the standard library in JavaScript that will do this for you.

It's possible to build your own, but it's a lot of work. You would have to build a parser and there are likely a lot of edge cases that you would have to solve for. It might be worth considering using a third-party module.

查看更多
趁早两清
3楼-- · 2020-07-10 08:52

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

  1. install node.js
  2. install the js-yaml package: npm install js-yaml -g

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));
查看更多
登录 后发表回答