Yamljs is a standalone JavaScript YAML 1.2 parser and encoder that possesses broad compatibility across node.js and all major browsers. Not only does it enable the conversion between YAML and JavaScript native objects, but it also provides command-line YAML/JSON conversion tools.
To use Yamljs in your JavaScript or Node.js project, you'll first need to import it. For browser-based implementations, link the yaml.js
script in your HTML page:
<script type="text/javascript" src="yaml.js"></script>
In a Node.js environment, install the yamljs
package via npm and require it in your file:
npm install yamljs
YAML = require('yamljs');
Here's how you can use Yamljs to parse a YAML string to a native JavaScript object:
nativeObject = YAML.parse(yamlString);
And to convert a native JavaScript object into a YAML string:
yamlString = YAML.stringify(nativeObject, 4);
If you want to load a YAML file directly, you can do so with the YAML.load
function:
nativeObject = YAML.load('myfile.yml');
Moreover, Yamljs can be utilized for command-line YAML/JSON conversions. Install it as a global npm module for easy command-line access:
npm install -g yamljs
This will offer you two commands: yaml2json
and json2yaml
, which allows for easy conversion between YAML and JSON formats respectively.
The documentation for Yamljs can be primarily found in its GitHub source (git://github.com/jeremyfa/yaml.js.git
). This includes necessary details about its functioning, compatibility, usage, and command-line tools. For more detailed help on its CLI tools, you can also look up the --help
option with yaml2json -h
or json2yaml -h
directly in your command line environment.