Yaml safe Json

written by zsombor on November 17th, 2006 @ 05:15 PM

First there was the great news JSON being subset of YAML. Great as it allows you to use Ruby’s YAML(Syck) parser to load JSON fragments, first step to Javascript-Ruby cross processing nirvana. Then sadly it turns out that whitespace ruins the party unless using a YAML safe outputter. Good news is that you can still munge JSON into YAML with a simple translation:

YAML.load(unsafe_json.gsub(/,"(\w+)"/, ', "\1"').gsub(/"(\w+)":/, '"\1": '))

Comments

  • neil on 17 Nov 17:15

    Extremely helpful, thanks a bunch!

  • david on 14 Apr 08:03

    Great hint. I needed to handle lists of dictionaries as well. I extended your regex by adding .gsub(/(\}),(\{)/, ’\1, \2’):

    YAML.load(unsafe_json.gsub(/,”(\w+)”/, ’, ”\1

Options:

Size

Colors