trnc
trnc

Reputation: 21577

Problem building JSON file

want to get all db entries by a specific hash and return it as json. I use the following code:

@tasks = Task.find_all_by_hash(params[:hash])

  respond_to do |format|
    format.json { render :json => @tasks }
  end

now i have the problem that my json file isn't correct. it has the following output:

[
{
task: {
hash: "9dfca619f00f5488785f6b74ad1b590beefaee7a88c04884bf197e7679f3"
id: 4
created_at: "2010-12-16T09:09:51Z"
updated_at: "2010-12-16T09:14:10Z"
done: true
name: "Hallo"
}
},
{
task: {
hash: "9dfca619f00f5488785f6b74ad1b590beefaee7a88c04884bf197e7679f3"
id: 5
created_at: "2010-12-16T09:12:37Z"
updated_at: "2010-12-16T09:12:37Z"
done: true
name: "Test"
}
},
...
]

but actually i want it like this:

{ tasks: [

{"id":"1","date_added":"0001-02-22 00:00:00","post_content":"Check out my content, this is loaded via ajax and parsed with JSON","author":"Ryan Coughlin"},

{"id":"2","date_added":"0000-00-00 00:00:00","post_content":"More content, loaded. Lets try to add a form in and post via ajax and append the new data","author":"Billy Bob"}

]}

any advice? thank you!

Upvotes: 0

Views: 414

Answers (1)

ssri
ssri

Reputation: 1300

Try collecting the task alone to an array and create a json object using that. Some thing like

@tasks = Task.find_all_by_hash(params[:hash])
a = []
  @tasks.each do |t|
  a << t[:task]
  end
  b = {:tasks => a}

 respond_to do |format|
  format.json { render :json => b }
end

Upvotes: 1

Related Questions