I'm surprised nobody pointed out JSON's []
method, which makes it very easy and transparent to decode and encode from/to JSON.
If object is string-like, parse the string and return the parsed result as a Ruby data structure. Otherwise generate a JSON text from the Ruby data structure object and return it.
Consider this:
require 'json'
hash = {"val":"test","val1":"test1","val2":"test2"} # => {:val=>"test", :val1=>"test1", :val2=>"test2"}
str = JSON[hash] # => "{\"val\":\"test\",\"val1\":\"test1\",\"val2\":\"test2\"}"
str
now contains the JSON encoded hash
.
It's easy to reverse it using:
JSON[str] # => {"val"=>"test", "val1"=>"test1", "val2"=>"test2"}
Custom objects need to_s
defined for the class, and inside it convert the object to a Hash then use to_json
on it.