I have the following:

create_table "events", options: "ENGINE=InnoDB DEFAULT CHARSET=latin1", force: :cascade do |t|
  t.string "meta_data"
end

When I open up Valentina Studio and look at the events table I can see one record:

ID           meta_data      
1         {"action"=>"bla"} 

When I call Event.last.meta_data I receive the following string:

"{\"action\"=>\"bla\"}

How can I get this string value without the escape characters? I've tried deep transforming and simply gsubbing but neither of these feel like I'm doing it right..

Thanks in advance

2 Answers

2
Tom Lord On Best Solutions

There aren't any escape characters.

What you're looking at is the representation of the string when inspected on the console.

Consider the following:

irb(main):001:0> x = '"hello"'
=> "\"hello\""
irb(main):002:0> puts x
"hello"

The string does not contain any backslashes. But when inspecting it, backslashes must be present in order to distinguish "end of string" vs "quotation mark, inside the string".

0
Mark On

The least ugly way I can do this is:

JSON.parse(string.gsub("=>", ":").gsub(":nil,", ":null,"))

If anyone has a less ugly way please let me know