1

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

3

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".

Sign up to request clarification or add additional context in comments.

5 Comments

Does that mean when I do calculations involving the string there will be no escape characters present?
There aren't any escape characters present.
Try using puts, to print the string to the console.
For another example, suppose you have x = "\n". When inspecting the value, you see \n displayed literally. But when printing it, you see this is displayed "normally" (as a new line). Inspecting strings is a much more convenient way of being able to tell, unambiguously, exactly what the real value is.
Yup - I can see now you need some way to distinguish quote marks included in the string vs quote marks denoting the start of the string - thanks again
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.