如何在Ruby中返回JSON? [英] How to return JSON in ruby?

查看:382
本文介绍了如何在Ruby中返回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

这篇关于如何在Ruby中返回JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆