代码之家  ›  专栏  ›  技术社区  ›  Luiz E.

如何从sql结果中对json进行分组

  •  0
  • Luiz E.  · 技术社区  · 12 年前

    我有一个从rails API返回的JSON,如下所示 [{"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"}]

    但我需要这样

    `[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"}]]

    我需要将结果分组在 empresa_id …我该怎么做?

    2 回复  |  直到 12 年前
        1
  •  3
  •   Kevin Lawrence    12 年前

    在模型的视图文件夹中,创建一个名为modelname.json.erb的文件。在这里,您可以使用ruby代码编辑json的格式。下面是一个未经测试的代码示例,说明它可能是什么样子:

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

    在你的控制器中,默认情况下,你会有这样的输出:

    format.json { render json: @modelname }
    

    将其更改为:

    format.json
    

    通过这样做,它将查找您刚刚创建的json视图!

        2
  •  2
  •   user904990 user904990    12 年前

    试试这个:

    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
    

    导致

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

    看见 live demo here