1JS-YAML - YAML 1.2 parser / writer for JavaScript 2================================================= 3 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) 6 7__[Online Demo](http://nodeca.github.com/js-yaml/)__ 8 9 10This is an implementation of [YAML](http://yaml.org/), a human-friendly data 11serialization language. Started as [PyYAML](http://pyyaml.org/) port, it was 12completely rewritten from scratch. Now it's very fast, and supports 1.2 spec. 13 14 15Installation 16------------ 17 18### YAML module for node.js 19 20``` 21npm install js-yaml 22``` 23 24 25### CLI executable 26 27If you want to inspect your YAML files from CLI, install js-yaml globally: 28 29``` 30npm install -g js-yaml 31``` 32 33#### Usage 34 35``` 36usage: js-yaml [-h] [-v] [-c] [-t] file 37 38Positional arguments: 39 file File with YAML document(s) 40 41Optional arguments: 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 46``` 47 48 49### Bundled YAML library for browsers 50 51``` html 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"> 56var doc = jsyaml.load('greeting: hello\nname: world'); 57</script> 58``` 59 60Browser support was done mostly for the online demo. If you find any errors - feel 61free to send pull requests with fixes. Also note, that IE and other old browsers 62needs [es5-shims](https://github.com/kriskowal/es5-shim) to operate. 63 64Notes: 65 661. 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. 682. `!!js/function` in browser bundle will not work by default. If you really need 69 it - load `esprima` parser first (via amd or directly). 703. `!!bin` in browser will return `Array`, because browsers do not support 71 node.js `Buffer` and adding Buffer shims is completely useless on practice. 72 73 74API 75--- 76 77Here we cover the most 'useful' methods. If you need advanced details (creating 78your 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 80info. 81 82``` javascript 83yaml = require('js-yaml'); 84fs = require('fs'); 85 86// Get document, or throw exception on error 87try { 88 var doc = yaml.safeLoad(fs.readFileSync('/home/ixti/example.yml', 'utf8')); 89 console.log(doc); 90} catch (e) { 91 console.log(e); 92} 93``` 94 95 96### safeLoad (string [ , options ]) 97 98**Recommended loading way.** Parses `string` as single YAML document. Returns a JavaScript 99object or throws `YAMLException` on error. By default, does not support regexps, 100functions and undefined. This method is safe for untrusted data. 101 102options: 103 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 throw on warnings if this function is not provided. 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. 120 121NOTE: This function **does not** understand multi-document sources, it throws 122exception on those. 123 124NOTE: JS-YAML **does not** support schema-specific tag resolution restrictions. 125So, the JSON schema is not as strictly defined in the YAML specification. 126It allows numbers in any notation, use `Null` and `NULL` as `null`, etc. 127The core schema also has no such restrictions. It allows binary notation for integers. 128 129 130### load (string [ , options ]) 131 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 135must additionally validate object structure to avoid injections: 136 137``` javascript 138var untrusted_code = '"toString": !<tag:yaml.org,2002:js/function> "function (){very_evil_thing();}"'; 139 140// I'm just converting that string, what could possibly go wrong? 141require('js-yaml').load(untrusted_code) + '' 142``` 143 144 145### safeLoadAll (string [, iterator] [, options ]) 146 147Same as `safeLoad()`, but understands multi-document sources. Applies 148`iterator` to each document if specified, or returns array of documents. 149 150``` javascript 151var yaml = require('js-yaml'); 152 153yaml.safeLoadAll(data, function (doc) { 154 console.log(doc); 155}); 156``` 157 158 159### loadAll (string [, iterator] [ , options ]) 160 161Same as `safeLoadAll()` but uses `DEFAULT_FULL_SCHEMA` by default. 162 163 164### safeDump (object [ , options ]) 165 166Serializes `object` as a YAML document. Uses `DEFAULT_SAFE_SCHEMA`, so it will 167throw an exception if you try to dump regexps or functions. However, you can 168disable exceptions by setting the `skipInvalid` option to `true`. 169 170options: 171 172- `indent` _(default: 2)_ - indentation width to use (in spaces). 173- `skipInvalid` _(default: false)_ - do not throw on invalid types (like function 174 in the safe schema) and skip pairs and single values with such types. 175- `flowLevel` (default: -1) - specifies level of nesting, when to switch from 176 block to flow style for collections. -1 means block style everwhere 177- `styles` - "tag" => "style" map. Each tag may have own set of styles. 178- `schema` _(default: `DEFAULT_SAFE_SCHEMA`)_ specifies a schema to use. 179- `sortKeys` _(default: `false`)_ - if `true`, sort keys when dumping YAML. If a 180 function, use the function to sort the keys. 181- `lineWidth` _(default: `80`)_ - set max line width. 182- `noRefs` _(default: `false`)_ - if `true`, don't convert duplicate objects into references 183- `noCompatMode` _(default: `false`)_ - if `true` don't try to be compatible with older 184 yaml versions. Currently: don't quote "yes", "no" and so on, as required for YAML 1.1 185- `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. 186 187The following table show availlable styles (e.g. "canonical", 188"binary"...) available for each tag (.e.g. !!null, !!int ...). Yaml 189output is shown on the right side after `=>` (default setting) or `->`: 190 191``` none 192!!null 193 "canonical" -> "~" 194 "lowercase" => "null" 195 "uppercase" -> "NULL" 196 "camelcase" -> "Null" 197 198!!int 199 "binary" -> "0b1", "0b101010", "0b1110001111010" 200 "octal" -> "01", "052", "016172" 201 "decimal" => "1", "42", "7290" 202 "hexadecimal" -> "0x1", "0x2A", "0x1C7A" 203 204!!bool 205 "lowercase" => "true", "false" 206 "uppercase" -> "TRUE", "FALSE" 207 "camelcase" -> "True", "False" 208 209!!float 210 "lowercase" => ".nan", '.inf' 211 "uppercase" -> ".NAN", '.INF' 212 "camelcase" -> ".NaN", '.Inf' 213``` 214 215Example: 216 217``` javascript 218safeDump (object, { 219 'styles': { 220 '!!null': 'canonical' // dump null as ~ 221 }, 222 'sortKeys': true // sort object keys 223}); 224``` 225 226### dump (object [ , options ]) 227 228Same as `safeDump()` but without limits (uses `DEFAULT_FULL_SCHEMA` by default). 229 230 231Supported YAML types 232-------------------- 233 234The list of standard YAML tags and corresponding JavaScipt types. See also 235[YAML tag discussion](http://pyyaml.org/wiki/YAMLTagDiscussion) and 236[YAML types repository](http://yaml.org/type/). 237 238``` 239!!null '' # null 240!!bool 'yes' # bool 241!!int '3...' # number 242!!float '3.14...' # number 243!!binary '...base64...' # buffer 244!!timestamp 'YYYY-...' # date 245!!omap [ ... ] # array of key-value pairs 246!!pairs [ ... ] # array or array pairs 247!!set { ... } # array of objects with given keys and null values 248!!str '...' # string 249!!seq [ ... ] # array 250!!map { ... } # object 251``` 252 253**JavaScript-specific tags** 254 255``` 256!!js/regexp /pattern/gim # RegExp 257!!js/undefined '' # Undefined 258!!js/function 'function () {...}' # Function 259``` 260 261Caveats 262------- 263 264Note, that you use arrays or objects as key in JS-YAML. JS does not allow objects 265or arrays as keys, and stringifies (by calling `toString()` method) them at the 266moment of adding them. 267 268``` yaml 269--- 270? [ foo, bar ] 271: - baz 272? { foo: bar } 273: - baz 274 - baz 275``` 276 277``` javascript 278{ "foo,bar": ["baz"], "[object Object]": ["baz", "baz"] } 279``` 280 281Also, reading of properties on implicit block mapping keys is not supported yet. 282So, the following YAML document cannot be loaded. 283 284``` yaml 285&anchor foo: 286 foo: bar 287 *anchor: duplicate key 288 baz: bat 289 *anchor: duplicate key 290``` 291 292 293Breaking changes in 2.x.x -> 3.x.x 294---------------------------------- 295 296If you have not used __custom__ tags or loader classes and not loaded yaml 297files via `require()`, no changes are needed. Just upgrade the library. 298 299Otherwise, you should: 300 3011. Replace all occurrences of `require('xxxx.yml')` by `fs.readFileSync()` + 302 `yaml.safeLoad()`. 3032. rewrite your custom tags constructors and custom loader 304 classes, to conform the new API. See 305 [examples](https://github.com/nodeca/js-yaml/tree/master/examples) and 306 [wiki](https://github.com/nodeca/js-yaml/wiki) for details. 307 308 309License 310------- 311 312View the [LICENSE](https://github.com/nodeca/js-yaml/blob/master/LICENSE) file 313(MIT). 314