Forum: Ruby on Rails to_json adds double quote to beginning and end of string

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Carl H. (Guest)
on 2007-04-13 20:41
(Received via mailing list)
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
Ball, Donald A Jr (Library) (Guest)
on 2007-04-13 20:54
(Received via mailing list)
> 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
Eden L. (Guest)
on 2007-04-15 12:59
(Received via mailing list)
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
This topic is locked and can not be replied to.