【问题标题】:Is it a bug for method hash#to_json in Rails?它是 Rails 中方法 hash#to_json 的错误吗?
【发布时间】:2010-07-17 06:13:00
【问题描述】:

我使用 Rails 2.3.8

  def index
    @posts = Post.all

    respond_to do |format|
      format.html # index.html.erb
      format.json { render :json => ({ :results => @posts.size, :rows => @posts.to_json(:only => [:id, :title, :click_count, :body])}).to_json }
    end
  end

生成的json数据为:

{"rows":"[{\"title\":\"ruby\",\"body\":\"good\",\"click_count\":1, \"id\":1},{\"title\":\"g\",\"body\":\"h\",\"click_count\":1,\"id\":2} ]","结果":2}

但实际上应该是:

{"rows":[{\"title\":\"ruby\",\"body\":\"good\",\"click_count\":1,\"id\":1} ,{\"title\":\"g\",\"body\":\"h\",\"click_count\":1,\"id\":2}],"results":2}

这是 Rails 中的错误吗?

现在 to_json 如何为我生成预期的 json 数据?

谢谢!

【问题讨论】:

  • 两者一模一样。
  • @stephenjudkins:第一个示例中的 rows 数组用引号引起来。那仍然是一个 JSON 数组吗? (我自己也不清楚,只是问问而已。)
  • @stephp,不,不一样,因为我在 extjs 网格面板中测试它,第二个 json 数据正在工作,但第一个失败。 [] 引用的不是 js 数组,它是字符串!

标签: ruby-on-rails ruby json


【解决方案1】:

对不起,是我的错。

动作代码应该是

  def index
    @posts = Post.all

    respond_to do |format|
      format.html # index.html.erb
      format.json { render :json => ({ :results => @posts.size, :rows => @posts.map{|x| x.attributes}).to_json } }
    end
  end

也就是说:key :rows 的值必须是数组对象!

谢谢hoooopo!

【讨论】:

    猜你喜欢
    • 2011-04-13
    • 1970-01-01
    • 1970-01-01
    • 2013-03-26
    • 2012-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多