json在Rails中返回字符串而不是json

json在Rails中返回字符串而不是json

本文介绍了to_json在Rails中返回字符串而不是json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面这段代码应该返回一个json:

  @series = @ series.map do | serie | {
:name => serie.name,
:id => serie.id
}

@ series.to_json

返回如下:

 [{\name \:\Barra \,\ id \:3},{\name \:\Botafogo 1 \,\id \:1},{\name \:\ Botafogo 2 \,\id \:2},{\name \:\Tijuca \,\id \:4}]

为什么它返回一个字符串而不是json?



'json'gem同时安装在我的.rb文件的顶部。

。出于某种原因 as_json 做我想要的,而不是 to_json 。我不明白为什么。如果我知道,我会更新我的答案。
奇怪的是,在将我的开发数据库表格sqlite 3更改为postgresql之前, to_json 工作正常。但我不认为这可能是问题所在,因为它与Heroku的postgre数据库配合得很好。


The following piece of code should return a json:

  @series = @series.map do |serie| {
    :name => serie.name,
    :id => serie.id
  }

  @series.to_json

It's return is the following:

"[{\"name\":\"Barra\",\"id\":3},{\"name\":\"Botafogo 1\",\"id\":1},{\"name\":\"Botafogo 2\",\"id\":2},{\"name\":\"Tijuca\",\"id\":4}]"

Why is it returning a string instead of a json?

'json' gem is both installed and required at the top of my .rb file

解决方案

I've just resolved my problem. For some reason as_json does what I want rather than to_json. I didn't quite understand why. I'll update my answer if I ever find out.That's strange, for to_json worked before I changed my development database form sqlite 3 to postgresql. But I don't think that might be the problem, because it was working nicely with Heroku's postgre database.

这篇关于to_json在Rails中返回字符串而不是json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 01:39