Created
June 20, 2016 03:18
-
-
Save image72/f60f2c33556975061bc1f698dd811869 to your computer and use it in GitHub Desktop.
parse YAML to JSON
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;(function(){ | |
YAML = { | |
valueOf: function(token) { | |
return eval('(' + token + ')') | |
}, | |
tokenize: function(str) { | |
return str.match(/(---|true|false|null|#(.*)|\[(.*?)\]|\{(.*?)\}|[\w\-]+:|-(.+)|\d+\.\d+|\d+|\n+)/g) | |
}, | |
strip: function(str) { | |
return str.replace(/^\s*|\s*$/, '') | |
}, | |
parse: function(tokens) { | |
var token, list = /^-(.*)/, key = /^([\w\-]+):/, stack = {} | |
while (token = tokens.shift()) | |
if (token[0] == '#' || token == '---' || token == "\n") | |
continue | |
else if (key.exec(token) && tokens[0] == "\n") | |
stack[RegExp.$1] = this.parse(tokens) | |
else if (key.exec(token)) | |
stack[RegExp.$1] = this.valueOf(tokens.shift()) | |
else if (list.exec(token)) | |
(stack.constructor == Array ? | |
stack : (stack = [])).push(this.strip(RegExp.$1)) | |
return stack | |
}, | |
eval: function(str) { | |
return this.parse(this.tokenize(str)) | |
} | |
} | |
})() | |
print(YAML.eval(readFile('config.yml')).toSource()) | |
// config.yml | |
` | |
--- | |
# just a comment | |
list: ['foo', 'bar'] | |
hash: { foo: "bar", n: 1 } | |
lib: | |
- lib/cart.js | |
- lib/cart.foo.js | |
specs: | |
- spec/cart.spec.js | |
- spec/cart.foo.spec.js | |
# - Commented out | |
environments: | |
all: | |
options: | |
failuresOnly: true | |
verbose: false | |
` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment