UNPKG

6.6 kBMarkdownView Raw
1JS-YAML - YAML 1.2 parser and serializer for JavaScript
2=======================================================
3
4[![Build Status](https://secure.travis-ci.org/nodeca/js-yaml.png)](http://travis-ci.org/nodeca/js-yaml)
5
6[Online Demo](http://nodeca.github.com/js-yaml/)
7
8
9This is an implementation of [YAML](http://yaml.org/), a human friendly data
10serialization language. Started as [PyYAML](http://pyyaml.org/) port, it was
11completely rewritten from scratch. Now it's very fast, and supports 1.2 spec.
12
13
14Breaking changes in 1.x.x -> 2.0.x
15----------------------------------
16
17If your have not used __custom__ tags or loader classes - no changes needed. Just
18upgrade library and enjoy high parse speed.
19
20In other case, you should rewrite your tag constructors and custom loader
21classes, to conform new schema-based API. See
22[examples](https://github.com/nodeca/js-yaml/tree/master/examples) and
23[wiki](https://github.com/nodeca/js-yaml/wiki) for details.
24Note, that parser internals were completely rewritten.
25
26
27Installation
28------------
29
30### YAML module for node.js
31
32```
33npm install js-yaml
34```
35
36
37### CLI executable
38
39If you want to inspect your YAML files from CLI, install js-yaml globally:
40
41```
42npm install js-yaml -g
43```
44
45#### Usage
46
47```
48usage: js-yaml [-h] [-v] [-c] [-j] [-t] file
49
50Positional arguments:
51 file File with YAML document(s)
52
53Optional arguments:
54 -h, --help Show this help message and exit.
55 -v, --version Show program's version number and exit.
56 -c, --compact Display errors in compact mode
57 -j, --to-json Output a non-funky boring JSON
58 -t, --trace Show stack trace on error
59```
60
61
62### Bundled YAML library for browsers
63
64``` html
65<script src="js-yaml.min.js"></script>
66<script type="text/javascript">
67var doc = jsyaml.load('greeting: hello\nname: world');
68</script>
69```
70
71Browser support was done mostly for online demo. If you find eny errors - feel
72free to send pull requests with fixes. Also note, that IE and other old browsers
73needs [es5-shims](https://github.com/kriskowal/es5-shim) to operate.
74
75
76API
77---
78
79Here we cover the most 'useful' methods. If you need advanced details (creating
80your own tags), see [wiki](https://github.com/nodeca/js-yaml/wiki) and
81[examples](https://github.com/nodeca/js-yaml/tree/master/examples) for more
82info.
83
84In node.js JS-YAML automatically registers handlers for `.yml` and `.yaml`
85files. You can load them just with `require`. That's mostly equivalent to
86calling `load()` on fetched content of a file. Just with one string!
87
88``` javascript
89require('js-yaml');
90
91// Get document, or throw exception on error
92try {
93 var doc = require('/home/ixti/example.yml');
94 console.log(doc);
95} catch (e) {
96 console.log(e);
97}
98```
99
100
101### load (string [ , options ])
102
103Parses `string` as single YAML document. Returns a JavaScript object or throws
104`YAMLException` on error.
105
106NOTE: This function **does not** understands multi-document sources, it throws
107exception on those.
108
109options:
110
111- `filename` _(default: null)_ - string to be used as a file path in
112 error/warning messages.
113- `strict` _(default - false)_ makes the loader to throw errors instead of
114 warnings.
115- `schema` _(default: `DEFAULT_SCHEMA`)_ - specifies a schema to use.
116
117
118### loadAll (string, iterator [ , options ])
119
120Same as `load()`, but understands multi-document sources and apply `iterator` to
121each document.
122
123``` javascript
124var yaml = require('js-yaml');
125
126yaml.loadAll(data, function (doc) {
127 console.log(doc);
128});
129```
130
131
132### safeLoad (string [ , options ])
133
134Same as `load()` but uses `SAFE_SCHEMA` by default - only recommended tags of
135YAML specification (no JavaScript-specific tags, e.g. `!!js/regexp`).
136
137
138### safeLoadAll (string, iterator [ , options ])
139
140Same as `loadAll()` but uses `SAFE_SCHEMA` by default - only recommended tags of
141YAML specification (no JavaScript-specific tags, e.g. `!!js/regexp`).
142
143
144### dump (object [ , options ])
145
146Serializes `object` as YAML document.
147
148options:
149
150- `indent` _(default: 2)_ - indentation width to use (in spaces).
151- `flowLevel` (default: -1) - specifies level of nesting, when to switch from
152 block to flow style for collections. -1 means block style everwhere
153- `styles` - "tag" => "style" map. Each tag may have own set of styles.
154- `schema` _(default: `DEFAULT_SCHEMA`)_ specifies a schema to use.
155
156styles:
157
158``` none
159!!null
160 "canonical" => "~"
161
162!!int
163 "binary" => "0b1", "0b101010", "0b1110001111010"
164 "octal" => "01", "052", "016172"
165 "decimal" => "1", "42", "7290"
166 "hexadecimal" => "0x1", "0x2A", "0x1C7A"
167
168!!null, !!bool, !!float
169 "lowercase" => "null", "true", "false", ".nan", '.inf'
170 "uppercase" => "NULL", "TRUE", "FALSE", ".NAN", '.INF'
171 "camelcase" => "Null", "True", "False", ".NaN", '.Inf'
172```
173
174By default, !!int uses `decimal`, and !!null, !!bool, !!float use `lowercase`.
175
176
177### safeDump (object [ , options ])
178
179Same as `dump()` but uses `SAFE_SCHEMA` by default - only recommended tags of
180YAML specification (no JavaScript-specific tags, e.g. `!!js/regexp`).
181
182
183Supported YAML types
184--------------------
185
186The list of standard YAML tags and corresponding JavaScipt types. See also
187[YAML tag discussion](http://pyyaml.org/wiki/YAMLTagDiscussion) and
188[YAML types repository](http://yaml.org/type/).
189
190```
191!!null '' # null
192!!bool 'yes' # bool
193!!int '3...' # number
194!!float '3.14...' # number
195!!binary '...base64...' # buffer
196!!timestamp 'YYYY-...' # date
197!!omap [ ... ] # array of key-value pairs
198!!pairs [ ... ] # array or array pairs
199!!set { ... } # array of objects with given keys and null values
200!!str '...' # string
201!!seq [ ... ] # array
202!!map { ... } # object
203```
204
205**JavaScript-specific tags**
206
207```
208!!js/regexp /pattern/gim # RegExp
209!!js/undefined '' # Undefined
210!!js/function 'function () {...}' # Function
211```
212
213
214
215
216## Caveats
217
218Note, that you use arrays or objects as key in JS-YAML. JS do not allows objects
219or array as keys, and stringifies (by calling .toString method) them at the
220moment of adding them.
221
222``` yaml
223---
224? [ foo, bar ]
225: - baz
226? { foo: bar }
227: - baz
228 - baz
229```
230
231``` javascript
232{ "foo,bar": ["baz"], "[object Object]": ["baz", "baz"] }
233```
234
235Also, reading of properties on implicit block mapping keys is not supported yet.
236So, the following YAML document cannot be loaded.
237
238``` yaml
239&anchor foo:
240 foo: bar
241 *anchor: duplicate key
242 baz: bat
243 *anchor: duplicate key
244```
245
246## License
247
248View the [LICENSE](https://github.com/nodeca/js-yaml/blob/master/LICENSE) file
249(MIT).