Reputation: 811
I want to convert a json string to yaml format in javascript. I was searching on google for the last two days but couldn't find any solution or libraries. There are answers available for java but not for javascript.
Suppose I have a json string like this:
{
"json": [
"fat and rigid"
],
"yaml": [
"skinny and flexible"
],
"object": {
"array": [
{
"null_value": null
},
{
"boolean": true
},
{
"integer": 1
}
]
}
}
converted to yaml:
json:
- fat and rigid
yaml:
- skinny and flexible
object:
array:
- null_value:
- boolean: true
- integer: 1
There is an online converter http://www.json2yaml.com/ , but how can I convert to it in javascript?
Upvotes: 28
Views: 63070
Reputation: 10826
In the browser:
<script type="module">
const sampleJson = `{"key": "value", "key2":{"key3":["value3", "value3"]}}`;
const result = (await import('https://cdn.jsdelivr.net/npm/[email protected]/browser/index.min.js'))
.stringify(JSON.parse(sampleJson));
console.log(result);
</script>
or:
<script type="text/javascript">
(async ()=>{
const sampleJson = `{"key": "value", "key2":{"key3":["value3", "value3"]}}`;
const result = (await import('https://cdn.jsdelivr.net/npm/[email protected]/browser/index.min.js'))
.stringify(JSON.parse(sampleJson));
console.log(result);
})()
</script>
Console/snippets:
To run the same in the devtools console or as a chromium content snippet, just remove the <script type="module">
tag. (note: for some reason this only works when the address bar targets a server page or localhost, but not a local file or empty url)
Upvotes: 0
Reputation: 3254
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
Upvotes: 26
Reputation: 419
You can use the 'js-yaml' npm package. It is officially recognized by yaml.org.
To then generate a YAML string from an object, you can use the following method:
yaml.dump(JSON.parse("yourJsonString"));
The full documentation for this method is available here: dump().
Upvotes: 21
Reputation: 41
Here is how to do it :)
import * as YAML from 'yaml';
const YAMLfile = YAML.stringify(JSONFILE);
And if you want to create a YAML file, you do it with de FS.
import * as fs from 'fs';
fs.writeFileSync('./fileName.yaml', YAMLfile);
Upvotes: 4
Reputation: 177
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}
Upvotes: 3