【问题标题】:Rails rendering JSON --> Square Brakets?Rails 渲染 JSON --> 方括号?
【发布时间】:2011-05-14 22:56:11
【问题描述】:

我使用 json 渲染一些对象:

def index
  if user_signed_in?
   @todos = current_user.todos.find_all()
   render :json => @todos
  else
    return nil
  end
end

它实际上是这样做的,但是有一个问题。我在 json 输出周围得到方括号 [],并且一些插件或 json 查看器因此无法读取它。这里有一些示例输出:

[{"todo":{"name":"Test todo","created_at":"2010-11-24T07:40:07Z","updated_at":"2010-11-24T07:40:07Z","done":0,"id":1,"user_id":1}},{"todo":{"name":"Ali Test","created_at":"2010-11-24T07:40:30Z","updated_at":"2010-11-24T07:40:30Z","done":0,"id":2,"user_id":1}}]

提前致谢!

【问题讨论】:

  • find_all 返回一个数组,所以这正是您应该期待的 JSON。
  • 啊,好吧。那么我怎样才能渲染所有实际有这些数组括号的条目呢?
  • @todos.each{|t| t.to_json} 会给你一个可以单独渲染的 json 对象数组。
  • @todos.each{|t| t.to_json} 在 jbuilder 视图中的 rails 4.2.5 中完美运行。谢谢 aceofspades!

标签: ruby-on-rails json rendering


【解决方案1】:

你试过了吗?

render :json => @todos.to_json

【讨论】:

    【解决方案2】:

    要获得您期望的 JSON 输出,您需要呈现一个 Hash 而不是 Array。 这是一篇关于转换的深入帖子:

    What is the best way to convert an array to a hash in Ruby

    用 OP 语法快速总结:

     render :json => Hash[*@todos.flatten]
    

    或者对于非对称数组

    render :json => Hash[@todos.map {|key, value| [key, value]}]
    

    在某些情况下,虽然这会添加您不想要的额外空值,但您可能必须分解数组并将其展平,或者尽可能简单地使用 Hash[ 而不是 [。

    【讨论】:

      猜你喜欢
      • 2015-08-04
      • 1970-01-01
      • 1970-01-01
      • 2013-07-24
      • 1970-01-01
      • 1970-01-01
      • 2021-11-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多