Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting JSON output using map method - Rails 3

I'm lacking some understanding on using the map method.

Using json output with no mapping

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

gives me the following output

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

using json with mapping

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

gives me this output

["bathroom renovations"]

How can I get my output to look like

[{"id":"1","name":"bathroom renovations"}]
like image 760
Robert B Avatar asked Mar 07 '26 15:03

Robert B


1 Answers

I think the following may work for you:

  format.json {render json: @categories.map{|category| {:id => category.id, :name =>  category.name} }}
like image 96
HungryCoder Avatar answered Mar 09 '26 11:03

HungryCoder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!