我有一个students
的Ruby数组。 Student
类包含id
,name
和age
属性。
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}
答案 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"}