rj487
rj487

Reputation: 4634

Rails format json

I got a format like this structure in my rails controller, and I need to do sth magic to arrange that.

[
[0] {
        :id => 29435,
  :question => q1,
    :groups => [
      [0] {
               :id => 12873,
       :class_name => "Class_1"
      }
    ]
},
[1] {
        :id => 29438,
  :question => q2,
    :groups => [
      [0] {
                :id => 12873,
        :class_name => "Class_1" 
      }
    ]
},
[2] {
        :id => 29443,
  :question => q3,
    :groups => [
      [0] {
                :id => 12876,
        :class_name => "Class_1"
      }
    ]
}
]

Then I need to check the [:groups][:id], if it match, I need to put their question in the same array. Finally, I need to reformat to json like this structure

"class": [
  {
    "id": 12873,
    "name": "Class_1",
    "question": ["q1","q2"]
  },
  {
    "id": 12876,
    "name": "Class_2",
    "question": ["q3"]
  }
]

Upvotes: 0

Views: 72

Answers (1)

Pragash
Pragash

Reputation: 753

If I imagine the input disctionary is an array called array then, the code would be like follows,

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

if you do refined_array.to_json you would get the following string

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

Hope this helps you.

Upvotes: 1

Related Questions