Rails格式为json

时间:2016-08-08 09:13:41

标签: ruby-on-rails json

我的rails控制器中有一个类似这种结构的格式,我需要做一些魔术来安排它。

[:groups][:id]

然后我需要检查json,如果匹配,我需要将他们的问题放在同一个数组中。最后,我需要重新格式化为"class": [ { "id": 12873, "name": "Class_1", "question": ["q1","q2"] }, { "id": 12876, "name": "Class_2", "question": ["q3"] } ] ,就像这个结构一样

    <div class = option1> <a href="#point1">
      <i class="fa fa-arrow-circle-right" aria-hidden="true"></i></a>
    </div>
    <div class = page2>
       <div class='land7'>
          <img src='images/land7.png'>
     </div>
        <div class="option2">
           <a href="#point2">
             <i class="fa fa-arrow-circle-left" aria-hidden="true"></i>
           </a>
       </div> 
    <div class='option3'>
      <a href="#point3">
        <i class="fa fa-arrow-circle-right" aria-hidden="true"></i>
      </a>
   </div>
    <div id = point1> </div>
      <div id='point4'> </div>
   </div> 
     <div class="page3">
         <div class='land8'>
             <img src='images/land8.png'>
     </div>
        <div class='option4'>
           <a href="#point4">
             <i class="fa fa-arrow-circle-left" aria-hidden="true"></i>
               </a>
         <div id='point3'> </div>
       </div>

1 个答案:

答案 0 :(得分:1)

如果我想输入的disctionary是一个名为 array 的数组,那么代码将如下所示,

refined_array = []

array.each do |a|
  a[:groups].each do |grp|    
    element = refined_array.select{|x| x['id'].to_i == grp[:id].to_i}

    has_found = element.length > 0

    element = has_found ? element.first : {'id' => grp[:id], 'question' => []}
    element['name'] = grp[:class_name]
    element['question'] << a[:question]

    refined_array << element unless has_found
  end
end

如果您执行 refined_array.to_json ,您将获得以下字符串

[{"id":12873,"question":["This is a question 1?"],"name":"Class_1"},{"id":12876,"question":["This is a question 2?","This is a question 3?"],"name":"Class_2"}]

希望这会对你有所帮助。