【问题标题】:Problem building JSON file构建 JSON 文件的问题
【发布时间】:2010-12-16 10:42:51
【问题描述】:

想要通过特定哈希获取所有数据库条目并将其作为 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"}

]}

有什么建议吗?谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby json format


    【解决方案1】:

    尝试将任务单独收集到一个数组并使用它创建一个 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-28
      • 1970-01-01
      • 1970-01-01
      • 2020-04-03
      • 1970-01-01
      • 1970-01-01
      • 2018-04-18
      • 1970-01-01
      相关资源
      最近更新 更多