Parsing Ruby hash literal using Javascript

2019-08-07 01:04发布

问题:

I need to take raw client text in a web form and send it back to a Tomcat servlet as JSON. For legacy reasons, this input may be formatted as a Ruby hash. I also cannot force my clients to convert their existing Ruby formatted inputs over to JSON. I could write a custom parser, but I wanted to see if a JavaScript based solution existed that would allow me to determine if a blob of text is a Ruby hash and, if so, convert it into JSON.

回答1:

JSON is a Ruby standard library. You've to just require it:

require 'json'

data = {:hello => "goodbye"}
p data.to_json #=> "{\"hello\":\"goodbye\"}"

Ref: Generating JSON