如何在Ruby中返回JSON?

人气:1,111 发布:2022-10-16 标签: ruby-on-rails json

问题描述

在Rails控制台中,如果我输入:

In the rails console if I type:

User.all.to_json

我得到以下退货.

"[{\"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\"}]"

将其复制/粘贴到http://jsonviewer.stack.hu/并尝试将其查看为JSON时,出现错误消息无效的JSON变量".我相信这是因为'\'字符.有关如何解决此问题的任何建议?

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?

推荐答案

如果在控制台中执行此操作,则输出包含多个引号和反斜杠是正常的".

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

在我的irb控制台中:

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\"}}"

但是使用方法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

825