To_json adds double quote to beginning and end of string


#1

Hello all,

I have a question regarding the to_json function. If I create a string
in script/console, and then apply the to_json method, it will take the
first and last double quote as part of the string. Is this behaviour
normal?

eg:

test = “my string”
test.to_json will return ““my string””

Regards,
Carl


#2

I have a question regarding the to_json function. If I create
a string in script/console, and then apply the to_json
method, it will take the first and last double quote as part
of the string. Is this behaviour normal?

eg:

test = “my string”
test.to_json will return ““my string””

Yep. The rails console is printing test.to_json as a string value like
any other. Notice if you output the test variable itself, being a string
value, it’s surrounded by double quotes. The same thing happens to
test.to_json, with the added wrinkle that the value contains actual
double quote characters, which are escaped for display.

  • donald

#3

It’s not taking the first and last double quote as part of the string,
per say. It’s just generating a valid JSON object for you. In the
case of a bare words like: my string, the JSON would be “my string”.

‘blah’.to_json
=> ““blah””

puts ‘blah’.to_json
“blah”
=> nil