views:

1343

answers:

3

Does such a thing exist for YAML (aka YAML)?

If this existed at one time, it must have been obliterated because the latest search turned up nada. It looks like there are plenty of implementations that dump from Javascript to YAML output only, but having trouble finding an implementation that supports both dump and load.

Is anyone working on such a thing ... or is the demand simply far too low for this.

+1  A: 

yaml-javascript pretends to be both dumper and parser. Never tried.

jetxee
Unfortunately, that project doesn't seem to go past pretend on output dumping. Thanks for the reply though.
dreftymac
Thank you for trying.
jetxee
+3  A: 

Was just looking for the same, here's a basic Javascript-based YAML parser written by Tj Holowaychuk over at refactormycode.com. I'm duplicating it here to ensure it isn't lost, appears the JsYaml link on yaml.org has been broken a while. Haven't tested it yet.

;(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
Matt Gardner
Great, thanks for the post.
dreftymac
+3  A: 

Possibly newer version of js-yaml here:

http://github.com/visionmedia/js-yaml

Paul Brannan