[英]Rails: How to add data header in csv file if different attributes are there in Json?
I have a array of data which is我有一组数据,它是
user: [
{name: 'foo', email: 'foo@gmail.com'},
{name: 'foo', email: 'foo@gmail.com', phone: '76767676'},
{name: 'foo', email: 'foo@gmail.com', pin_code: '22526'},
]
and I am changing it into csv by this code我正在通过此代码将其更改为 csv
CSV.open(file, 'w') do |csv|
user_hash = JSON.parse(user.to_json)
csv << user_hash.first.keys
user_hash.each do |hash|
csv << hash.values
end
end
in above code there is a problem that i am taking user_hash.first.keys so first keys name and email will be there for header.在上面的代码中有一个问题,我正在使用 user_hash.first.keys 所以第一个键名和电子邮件将在标题中。
I want to know that how can we add new column in header if a new attribute arrives which is happening in other two.我想知道如果其他两个中发生的新属性到达,我们如何在标题中添加新列。
because I am taking the user_hash.first.keys so name and email header columns will be there not phone and pin_code.因为我正在使用 user_hash.first.keys,所以名称和电子邮件标题列将不存在电话和 pin_code。
Thanks.谢谢。
You will need to collect all available keys first and then get the values for those keys in the same order for each hash.您需要首先收集所有可用的键,然后以相同的顺序为每个散列获取这些键的值。
user_hash = JSON.parse(user.to_json)
keys = user_hash.flat_map(&:keys).uniq
CSV.open(file, 'w') do |csv|
csv << keys
user_hash.each { |hash| csv << hash.values_at(*keys) }
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.