2010-11-24 92 views
-1

我渲染某些对象使用JSON:Rails渲染JSON - > Square Brakets?

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}}] 

在此先感谢!

+1

find_all返回一个数组,所以这正是您应该期待的JSON。 – aceofspades 2010-11-29 02:54:47

+0

啊好吧。所以我怎么能渲染所有条目实际上有这些阵列布拉克? – Tronic 2010-11-29 07:01:57

回答

0

你试过了吗?

render :json => @todos.to_json 
0

要获得JSON输出,您期望您需要呈现散列而不是阵列。 下面是一个深入交上转换:

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]}] 

在某些情况下,虽然这增加了你不想要的额外的空值,你可能不得不打破你的阵列并将其平坦化,或者简单地使用散列[而不是[当有可能。