How to reformat JSON in rails -
i trying out d3.js rails app give me pretty graphs. 1 of graphs trying out forced directed graph. in order create json needs in format
{ "nodes":[ {"name":"myriel"}, {"name":"napoleon"}, {"name":"mlle.baptistine"}, {"name":"mme.magloire"} ], "links":[ {"source":1,"target":0,"value":1}, {"source":2,"target":0,"value":8}, {"source":3,"target":0,"value":10}, {"source":3,"target":2,"value":6} ] }
i have produced json database using query:
user.joins("inner join relationships on users.id = relationships.user_id").select(" users.name, relationships.source, relationships.target,relationships.value")
which created in controller follows
def index render :json => user.joins("inner join relationships on users.id = relationships.user_id").select(" users.name, relationships.source, relationships.target,relationships.value") end end
and result looks this:
[{"name":"myriel","source":121,"target":1,"value":1},{"name":"napoleon","source":119,"target":2,"value":2}, {"name":"myriel","source":121,"target":1,"value":2},{"name":"myriel","source":121,"target":3,"value":1},{"name":"mlle.baptistine","source":122,"target":2,"value":3}]
is there simple way map json need?
as suggested in answer, create class method:
class user def self.including_relationships user.joins("inner join relationships on users.id = relationships.user_id").select("users.name, relationships.user_id, relationships.target,relationships.value").each_with_object(hash.new{|h, k| h[k] = []}) |a, obj| obj['nodes'] << a.slice('name') obj['links'] << a.slice('source', 'target', 'value') end end end
then in controller:
def index render :json => user.including_relationships end
i named method including_relationships
since not creating json instead converting data hash
object, can name wish.
Comments
Post a Comment