Search code examples
ruby-on-railsrubypostgresqlhashhstore

how to get 2-d hash as an output from hstore column?


In rails app I try to store 2-d hash in postgreSql hstore column, but for output I get something like

{"6/5"=>"{\"color\"=>\"white\"}", "8/1"=>"{\"color\"=>\"white\"}", "8/2"=>"{\"color\"=>\"white\"}", "8/3"=>"{\"color\"=>\"white\"}"}.

How can I get 2-d hash as output or maybe you can give some advice for how to parse it?.


Solution

  • If you need to convert this into hash here is how you could it do:

    str = {"6/5"=>"{\"color\"=>\"white\"}", "8/1"=>"{\"color\"=>\"white\"}", "8/2"=>"{\"color\"=>\"white\"}", "8/3"=>"{\"color\"=>\"white\"}"}
    p str.each_with_object({}){|(k,v),h| h[k] = eval(v)}
    

    Result

    {"6/5"=>{"color"=>"white"}, "8/1"=>{"color"=>"white"}, "8/2"=>{"color"=>"white"}, "8/3"=>{"color"=>"white"}}