Home > Mobile >  how to convert string of object to object in rails
how to convert string of object to object in rails

Time:12-22

How can I convert this string of object to just object.

// object inside string

"{\"text\"=>\"ID\", \"value\"=>\"id\"}"

// object

{"text"=>"ID", "value"=>"id"}

CodePudding user response:

You can go with this

require 'json'

def string_parse_to_hash(string)
  modified_string = string
    .gsub(/:(\w )/){"\"#{$1}\""}
    .gsub('=>', ':')
    .gsub("nil", "null")
  JSON.parse(modified_string)
rescue
  {}
end

str = "{\"text\"=>\"ID\", \"value\"=>\"id\"}"
puts string_parse_to_hash(str)

But be ware, if you don't trust the source of the string, you have to sanitize and validate its content.

CodePudding user response:

If you like to live dangerously, this is also an option:

str = "{\"text\"=>\"ID\", \"value\"=>\"id\"}"
parsed_hash = eval(str)
# {"text"=>"ID", "value"=>"id"}

but that is kinda very dangerous depending on where you get your input from.

eval literally evaluates your string as ruby code. So you could inject literally anything that would be very harmful

  • Related