dpst dpst - 2 months ago 5
JSON Question

How to reformat original data and then render a nested JSON request in Rails 4?

def index
@users = User.all
render json: @users
end


Which returns a json response like (in reality I have like 20 different attributes, this is just a subset):

{“id”:1, “name”:”John”, "city": "New York"},
{“id”:2, “name”:”Dave”, "city": "Chicago"},
{“id”:3, “name”:”Peter”, "city": "Beijing"}


However I want the response to be more like this:

{“id”:1, “name”{"name”,"John”, "id":1}, "city": "New York"},
{“id”:2, “name”{"name”,"Dave”, "id":2}, "city": "Chicago"},
{“id”:3, “name”{"name”,"Peter”, "id":3}, "city": "Beijing"}


So that when I iterate through the request I can access attributes like this:

name.id #will print 1
name.name #will print “John”
city #will print "New York"

Answer

just type it in brackets:

@users = User.all
render json: @users.map{ |k| {name: {name: k.name, id: k.id}, city: k.city} }
Comments