How to convert JSON to YAML in javascript

后端 未结 4 1013
伪装坚强ぢ
伪装坚强ぢ 2020-12-06 11:23

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 availa

相关标签:
4条回答
  • 2020-12-06 11:42

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

    0 讨论(0)
  • 2020-12-06 11:45

    I tried to package the answer to a bash script.

    #!/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}
    
    0 讨论(0)
  • 2020-12-06 11:47

    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.

    0 讨论(0)
  • 2020-12-06 12:04

    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
    
    0 讨论(0)
提交回复
热议问题