Luiz E.
Luiz E.

Reputation: 7229

how to group a json from a sql result

I have a JSON that's returned from my rails API like this [{"tipo":"1","dia":"02/10/2012","empresa_id":"17","horas":"0:15","tempo":"900"}, {"tipo":"2","dia":"02/10/2012","empresa_id":"17","horas":"0:12","tempo":"720"}]

but I need it to be something like this

`[empresa_id: 17, [{"tipo":"1","dia":"02/10/2012","horas":"0:15","tempo":"900"}, {"tipo":"2","dia":"02/10/2012","horas":"0:12","tempo":"720"}]]

I need to group the results within empresa_id...how do I do that?

Upvotes: 0

Views: 218

Answers (2)

user904990
user904990

Reputation:

Try this:

require 'json'

s = '[{"tipo":"1","dia":"02/10/2012","empresa_id":"17","horas":"0:15","tempo":"900"}, {"tipo":"2","dia":"02/10/2012","empresa_id":"17","horas":"0:12","tempo":"720"}]'
j = JSON.parse(s)
r = j.inject({}) do |f,c|
    key = c.delete('empresa_id')
    (f[key]||=[]) << c
    f
end
p r

resulting in

{"17"=>[{"tipo"=>"1", "dia"=>"02/10/2012", "horas"=>"0:15", "tempo"=>"900"}, {"tipo"=>"2", "dia"=>"02/10/2012", "horas"=>"0:12", "tempo"=>"720"}]}

See live demo here

Upvotes: 2

Kevin Lawrence
Kevin Lawrence

Reputation: 751

In your model's view folder, create a file called modelname.json.erb. Here, you can use ruby code to edit how you want to format your json. Here's an untested code example of what it might look like:

[
<% i = 0
@modelname.each do |model| %>
    {
        "id": <%= model.id %>,
        "name": "<%= model.name %>"
    }<% if i != (@modelname.size - 1) %>,<% end %>
    <% i += 1 %>
<% end %>
]

In your controller, by default you will have something like this for the output:

format.json { render json: @modelname }

Change it to this:

format.json

By doing this, it will look for the json view you just created!

Upvotes: 3

Related Questions