i render some object using json:
def index
if user_signed_in?
@todos = current_user.todos.find_all()
render :json => @todos
else
return nil
end
end
it actually does that, but there's a problem. I get square brakets [ ] arround the json output and some plugins or json viewers cannot read it because of them. Here some sample output:
[{"todo":{"name":"Te开发者_运维百科st 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}}]
thanks in advance!
Have you tried?
render :json => @todos.to_json
To get the JSON output you are expecting you need to render a Hash and not an Array. Here is an in-depth post on converting:
What is the best way to convert an array to a hash in Ruby
Quick summary with OP syntax:
render :json => Hash[*@todos.flatten]
or for an asymmetrical array
render :json => Hash[@todos.map {|key, value| [key, value]}]
In some cases though this adds extra nulls that you don't want and you may have to break your array down and flatten it or simply use Hash[ instead of [ whenever possible.
精彩评论