构建 JSON 文件时出现问题

发布于 2024-10-07 21:50:53 字数 1050 浏览 3 评论 0原文

想要通过特定哈希获取所有数据库条目并将其作为 json 返回。我使用以下代码:

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

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

现在我遇到的问题是我的 json 文件不正确。它有以下输出:

[
{
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"
}
},
...
]

但实际上我想要这样:

{ 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"}

]}

有什么建议吗?谢谢你!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

ヤ经典坏疍 2024-10-14 21:50:53

尝试将任务单独收集到一个数组中,并使用它创建一个 json 对象。有些事情就像

@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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文