1

I have a string. {"response_code"=>"SUCCESS", "authorisation_result"=>"Approved", "transaction_number"=>"1234567", "receipt_number"=>"999999", :cents=>100} that is stored as a value in hstore in postgresql.

So it's a raw string not a YAML or a JSON.
I was wonering how to get the value back to the hash that was used to insert the record.

The idea of using EVAL scares the hell out of me, because there is potential for use input here.


This question might seem to be a replica of How to convert a string to a hash in ruby/rails without using eval?, but the answer there doesn't mesh with the question. It only offers eval as the solution. (I don't understand how the answer was marked as the answer)
Community
  • 1
  • 1
baash05
  • 4,394
  • 11
  • 59
  • 97
  • Perhaps you could store JSON instead, then you can use JSON functions to safely convert the string back into a value. Are you actually storing Ruby source code in the database? – Greg Hewgill Oct 20 '14 at 01:41
  • The real answer is "stop using hstore, use PostgreSQL's json column type instead". – mu is too short Oct 20 '14 at 04:12

1 Answers1

3

Ruby hashes look pretty similar to JSON, so this would work for your example:

require 'json'

str = "{\"response_code\"=>\"SUCCESS\", \"authorisation_result\"=>\"Approved\", \"transaction_number\"=>\"1234567\", \"receipt_number\"=>\"999999\", :cents=>100}"

JSON.parse str.gsub(/:(\w+)/){"\"#{$1}\""}.gsub('=>', ':')
# => {"response_code"=>"SUCCESS", "authorisation_result"=>"Approved", "transaction_number"=>"1234567", "receipt_number"=>"999999", "cents"=>100}
August
  • 12,410
  • 3
  • 35
  • 51