簡體   English   中英

使用地圖方法格式化JSON輸出-Rails 3

[英]Formatting JSON output using map method - Rails 3

我對使用map方法缺乏了解。

使用不帶映射的json輸出

format.json  { render :json => @categories }

給我以下輸出

[{"created_at":"2012-10-20T01:16:35+11:00","id":1,"name":"bathroom renovations","updated_at":"2012-10-20T01:16:35+11:00"}]

將json與映射一起使用

format.json  { render :json => @categories.map(&:name) }

給我這個輸出

["bathroom renovations"]

我怎樣才能使輸出看起來像

[{"id":"1","name":"bathroom renovations"}]

我認為以下可能對您有用:

  format.json {render json: @categories.map{|category| {:id => category.id, :name =>  category.name} }}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM