从Ruby对象数组生成Key,Value JSON对象

时间:2017-12-07 16:00:16

标签: ruby-on-rails arrays json ruby

我有一个students的Ruby数组。 Student类包含idnameage属性。

students = [ 
             {id:"id1",name:"name1",age:"age1"}, 
             {id:"id2",name:"name2",age:"age2"},
             {id:"id3",name:"name3",age:"age3"}
           ]

我想从这个数组创建一个JSON键值对象,如下所示。

json_object = {id1:name1, id2:name2, id3:name3}

3 个答案:

答案 0 :(得分:3)

input = [ {id:"id1",name:"name1",age:"age1"},
          {id:"id2",name:"name2",age:"age2"},
          {id:"id3",name:"name3",age:"age3"}]

require 'json'
JSON.dump(input.map { |hash| [hash[:id], hash[:name]] }.to_h)
#⇒ '{"id1":"name1","id2":"name2","id3":"name3"}'

答案 1 :(得分:2)

您的数据完全相同,但如果您想生成一个以students[n][:id]为值的哈希值和students[n][:name]值作为值,则可以执行以下操作:

student_ids_to_names = students.each_with_object({}) do |student, memo|
  memo[student[:id]] = student[:name]
end

对于您的数据,由于学生完全相同,您最终只能输入一个条目:{ "id1" => "name1" }。如果数据不同,则每个密钥在:id上都是唯一的。

获得哈希后,可以调用json_object = students_ids_to_names.to_json来获取JSON字符串。

答案 2 :(得分:2)

放手一搏:

students = [ 
             {id:"id1",name:"name1",age:"age1"}, 
             {id:"id2",name:"name2",age:"age2"},
             {id:"id3",name:"name3",age:"age3"}
           ]

json_object = students.each_with_object({}) do |hsh, returning|
  returning[hsh[:id]] = hsh[:name]
end.to_json

在控制台中:

puts json_object
 => {"id1":"name1","id2":"name2","id3":"name3"}