Masatoshi Nishiguchi
Software Engineer

Jsonify Ruby Hash string

ruby json hash

Sometimes I have this issue of parsing JSON that contains the string representation of Ruby hash.

Problem

It happens obviously because the hash string is not JSON.

require 'json'
hsh_as_str = '{"order_id"=>nil}'
JSON.parse(hsh_as_str)
# JSON::ParserError: 783: unexpected token at '{"order_id"=>nil}'

Solution A

require 'json'
hsh_as_str = '{"order_id"=>nil}'
valid_json = hsh_as_str.gsub('=>', ':').gsub(':nil', ':null')
#=> "{\"order_id\":null}"
JSON.parse(valid_json)
#=> {"order_id"=>nil}

Solution B

require 'json'
hsh_as_str = '{"order_id"=>nil}'
eval(hsh_as_str)
#=> {"order_id"=>nil}

Pitfalls

'{"user"=>#<User id=123>}'

That’s it.