1 JS-YAML - YAML 1.2 parser / writer for JavaScript
2 =================================================
4 [![Build Status](https://travis-ci.org/nodeca/js-yaml.svg?branch=master)](https://travis-ci.org/nodeca/js-yaml)
5 [![NPM version](https://img.shields.io/npm/v/js-yaml.svg)](https://www.npmjs.org/package/js-yaml)
7 __[Online Demo](http://nodeca.github.com/js-yaml/)__
10 This is an implementation of [YAML](http://yaml.org/), a human-friendly data
11 serialization language. Started as [PyYAML](http://pyyaml.org/) port, it was
12 completely rewritten from scratch. Now it's very fast, and supports 1.2 spec.
18 ### YAML module for node.js
27 If you want to inspect your YAML files from CLI, install js-yaml globally:
30 npm install -g js-yaml
36 usage: js-yaml [-h] [-v] [-c] [-t] file
39 file File with YAML document(s)
42 -h, --help Show this help message and exit.
43 -v, --version Show program's version number and exit.
44 -c, --compact Display errors in compact mode
45 -t, --trace Show stack trace on error
49 ### Bundled YAML library for browsers
52 <!-- esprima required only for !!js/function -->
53 <script src="esprima.js"></script>
54 <script src="js-yaml.min.js"></script>
55 <script type="text/javascript">
56 var doc = jsyaml.load('greeting: hello\nname: world');
60 Browser support was done mostly for the online demo. If you find any errors - feel
61 free to send pull requests with fixes. Also note, that IE and other old browsers
62 needs [es5-shims](https://github.com/kriskowal/es5-shim) to operate.
66 1. We have no resources to support browserified version. Don't expect it to be
67 well tested. Don't expect fast fixes if something goes wrong there.
68 2. `!!js/function` in browser bundle will not work by default. If you really need
69 it - load `esprima` parser first (via amd or directly).
70 3. `!!bin` in browser will return `Array`, because browsers do not support
71 node.js `Buffer` and adding Buffer shims is completely useless on practice.
77 Here we cover the most 'useful' methods. If you need advanced details (creating
78 your own tags), see [wiki](https://github.com/nodeca/js-yaml/wiki) and
79 [examples](https://github.com/nodeca/js-yaml/tree/master/examples) for more
83 const yaml = require('js-yaml');
84 const fs = require('fs');
86 // Get document, or throw exception on error
88 const doc = yaml.safeLoad(fs.readFileSync('/home/ixti/example.yml', 'utf8'));
96 ### safeLoad (string [ , options ])
98 **Recommended loading way.** Parses `string` as single YAML document. Returns either a
99 plain object, a string or `undefined`, or throws `YAMLException` on error. By default, does
100 not support regexps, functions and undefined. This method is safe for untrusted data.
104 - `filename` _(default: null)_ - string to be used as a file path in
105 error/warning messages.
106 - `onWarning` _(default: null)_ - function to call on warning messages.
107 Loader will call this function with an instance of `YAMLException` for each warning.
108 - `schema` _(default: `DEFAULT_SAFE_SCHEMA`)_ - specifies a schema to use.
109 - `FAILSAFE_SCHEMA` - only strings, arrays and plain objects:
110 http://www.yaml.org/spec/1.2/spec.html#id2802346
111 - `JSON_SCHEMA` - all JSON-supported types:
112 http://www.yaml.org/spec/1.2/spec.html#id2803231
113 - `CORE_SCHEMA` - same as `JSON_SCHEMA`:
114 http://www.yaml.org/spec/1.2/spec.html#id2804923
115 - `DEFAULT_SAFE_SCHEMA` - all supported YAML types, without unsafe ones
116 (`!!js/undefined`, `!!js/regexp` and `!!js/function`):
117 http://yaml.org/type/
118 - `DEFAULT_FULL_SCHEMA` - all supported YAML types.
119 - `json` _(default: false)_ - compatibility with JSON.parse behaviour. If true, then duplicate keys in a mapping will override values rather than throwing an error.
121 NOTE: This function **does not** understand multi-document sources, it throws
124 NOTE: JS-YAML **does not** support schema-specific tag resolution restrictions.
125 So, the JSON schema is not as strictly defined in the YAML specification.
126 It allows numbers in any notation, use `Null` and `NULL` as `null`, etc.
127 The core schema also has no such restrictions. It allows binary notation for integers.
130 ### load (string [ , options ])
132 **Use with care with untrusted sources**. The same as `safeLoad()` but uses
133 `DEFAULT_FULL_SCHEMA` by default - adds some JavaScript-specific types:
134 `!!js/function`, `!!js/regexp` and `!!js/undefined`. For untrusted sources, you
135 must additionally validate object structure to avoid injections:
138 const untrusted_code = '"toString": !<tag:yaml.org,2002:js/function> "function (){very_evil_thing();}"';
140 // I'm just converting that string, what could possibly go wrong?
141 require('js-yaml').load(untrusted_code) + ''
145 ### safeLoadAll (string [, iterator] [, options ])
147 Same as `safeLoad()`, but understands multi-document sources. Applies
148 `iterator` to each document if specified, or returns array of documents.
151 const yaml = require('js-yaml');
153 yaml.safeLoadAll(data, function (doc) {
159 ### loadAll (string [, iterator] [ , options ])
161 Same as `safeLoadAll()` but uses `DEFAULT_FULL_SCHEMA` by default.
164 ### safeDump (object [ , options ])
166 Serializes `object` as a YAML document. Uses `DEFAULT_SAFE_SCHEMA`, so it will
167 throw an exception if you try to dump regexps or functions. However, you can
168 disable exceptions by setting the `skipInvalid` option to `true`.
172 - `indent` _(default: 2)_ - indentation width to use (in spaces).
173 - `noArrayIndent` _(default: false)_ - when true, will not add an indentation level to array elements
174 - `skipInvalid` _(default: false)_ - do not throw on invalid types (like function
175 in the safe schema) and skip pairs and single values with such types.
176 - `flowLevel` (default: -1) - specifies level of nesting, when to switch from
177 block to flow style for collections. -1 means block style everwhere
178 - `styles` - "tag" => "style" map. Each tag may have own set of styles.
179 - `schema` _(default: `DEFAULT_SAFE_SCHEMA`)_ specifies a schema to use.
180 - `sortKeys` _(default: `false`)_ - if `true`, sort keys when dumping YAML. If a
181 function, use the function to sort the keys.
182 - `lineWidth` _(default: `80`)_ - set max line width.
183 - `noRefs` _(default: `false`)_ - if `true`, don't convert duplicate objects into references
184 - `noCompatMode` _(default: `false`)_ - if `true` don't try to be compatible with older
185 yaml versions. Currently: don't quote "yes", "no" and so on, as required for YAML 1.1
186 - `condenseFlow` _(default: `false`)_ - if `true` flow sequences will be condensed, omitting the space between `a, b`. Eg. `'[a,b]'`, and omitting the space between `key: value` and quoting the key. Eg. `'{"a":b}'` Can be useful when using yaml for pretty URL query params as spaces are %-encoded.
188 The following table show availlable styles (e.g. "canonical",
189 "binary"...) available for each tag (.e.g. !!null, !!int ...). Yaml
190 output is shown on the right side after `=>` (default setting) or `->`:
195 "lowercase" => "null"
196 "uppercase" -> "NULL"
197 "camelcase" -> "Null"
200 "binary" -> "0b1", "0b101010", "0b1110001111010"
201 "octal" -> "01", "052", "016172"
202 "decimal" => "1", "42", "7290"
203 "hexadecimal" -> "0x1", "0x2A", "0x1C7A"
206 "lowercase" => "true", "false"
207 "uppercase" -> "TRUE", "FALSE"
208 "camelcase" -> "True", "False"
211 "lowercase" => ".nan", '.inf'
212 "uppercase" -> ".NAN", '.INF'
213 "camelcase" -> ".NaN", '.Inf'
221 '!!null': 'canonical' // dump null as ~
223 'sortKeys': true // sort object keys
227 ### dump (object [ , options ])
229 Same as `safeDump()` but without limits (uses `DEFAULT_FULL_SCHEMA` by default).
235 The list of standard YAML tags and corresponding JavaScipt types. See also
236 [YAML tag discussion](http://pyyaml.org/wiki/YAMLTagDiscussion) and
237 [YAML types repository](http://yaml.org/type/).
242 !!int '3...' # number
243 !!float '3.14...' # number
244 !!binary '...base64...' # buffer
245 !!timestamp 'YYYY-...' # date
246 !!omap [ ... ] # array of key-value pairs
247 !!pairs [ ... ] # array or array pairs
248 !!set { ... } # array of objects with given keys and null values
250 !!seq [ ... ] # array
251 !!map { ... } # object
254 **JavaScript-specific tags**
257 !!js/regexp /pattern/gim # RegExp
258 !!js/undefined '' # Undefined
259 !!js/function 'function () {...}' # Function
265 Note, that you use arrays or objects as key in JS-YAML. JS does not allow objects
266 or arrays as keys, and stringifies (by calling `toString()` method) them at the
267 moment of adding them.
279 { "foo,bar": ["baz"], "[object Object]": ["baz", "baz"] }
282 Also, reading of properties on implicit block mapping keys is not supported yet.
283 So, the following YAML document cannot be loaded.
288 *anchor: duplicate key
290 *anchor: duplicate key
294 js-yaml for enterprise
295 ----------------------
297 Available as part of the Tidelift Subscription
299 The maintainers of js-yaml and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-js-yaml?utm_source=npm-js-yaml&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)