简体   繁体   中英

How to return JSON in ruby?

In the rails console if I type:

User.all.to_json

I get the following returned.

"[{\"created_at\":\"2013-04-29T23:10:36Z\",\"email\":\"test@test.com\",\"id\":2,\"updated_at\":\"2013-04-29T23:10:36Z\"},{\"created_at\":\"2013-03-18T04:53:42Z\",\"email\":\"sharataka@gmail.com\",\"id\":1,\"updated_at\":\"2013-05-01T12:03:01Z\"}]"

When copy/paste this to http://jsonviewer.stack.hu/ and try to view it as JSON, I get an error saying 'Invalid JSON Variable'. I believe this is because of the '\\' characters. Any advice on how to fix this?

  • to_json returns a JSON string with escaped quotes etc.
  • as_json returns it as actual JSON, this is what would validate properly.

Which you use depends on how you're rendering it.

If you do that in your console, it's "normal" that the output contains several quotes and backslashes.

In my irb console:

irb(main):009:0> Patient.first.to_json
#=> "{\"patient\":{\"created_at\":\"2013-03-14T16:53:52-04:00\",\"id\":6538,\"updated_at\":\"2013-03-14T16:53:52-04:00\"}}"

But using the method puts :

irb(main):010:0> puts Patient.first.to_json
{"patient":{"created_at":"2013-03-14T16:53:52-04:00","id":6538,"updated_at":"2013-03-14T16:53:52-04:00"}}
#=> nil

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM