Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert JSON to YAML in javascript

I want to convert a json string to yaml format in javascript.I am trying my hand on google from last two days didnt found any solution or libraries. There are answers available for java but not for javascript.

Suppose i have json string like this:

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

conver to yaml:

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

There is a online converter http://www.json2yaml.com/ , but how to convert to it in javascript.

like image 255
sandeepKumar Avatar asked Aug 05 '16 05:08

sandeepKumar


3 Answers

You can use yaml NPM package.

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());

Output

version: 1.0.0
dependencies:
  yaml: ^1.10.0
package:
  exclude:
    - .idea/**
    - .gitignore
like image 163
Pujan Avatar answered Sep 19 '22 23:09

Pujan


Use the 'js-yaml' npm package! That's the one that is officially recognized by yaml.org. (If you want to be extra sure && this post is outdated, go check yaml.org yourself to see which package it recommends.) I initially used 'json2yaml' instead and got strange parsing behavior when converting json (as string) to yaml.

like image 31
Tamiko Avatar answered Sep 18 '22 23:09

Tamiko


If someone still wants to convert JSON to YAML, you may use this JavaScript library: https://www.npmjs.com/package/json2yaml

like image 37
dube Avatar answered Sep 21 '22 23:09

dube