英文:
Rails + Read XLSX or CSV without fixed headers and key value pair
问题
在Rails中尝试读取没有固定标题的XLSX / CSV文件。
例如
第一个CSV文件,标题将类似于user_id、email、dob
第二个CSV文件,标题将类似于user_id、username、email
因此,系统应该能够正确读取它们,并应该创建正确的JSON,如下所示
对于第一个文件,JSON将如下所示
{
"user_id": 1,
"email": "example@eample.com",
"dob": "2001-01-01",
}
对于第二个文件,JSON将如下所示
{
"user_id": 1,
"email": "example@eample.com",
"username": "example"
}
英文:
In Rails trying to read XLSX / CSV file without fixed headers.
For example
1st CSV File, the header will be like user_id, email, dob
2nd CSV File, the header will be like user_id, username, email
So the system should manage to read them properly and should create proper json like
For the First File, JSON will be like
{
"user_id": 1,
"email": "example@eample.com",
"dob": "2001-01-01",
}
For the Second File, JSON will be like
{
"user_id": 1,
"email": "example@eample.com",
"username": "example"
}
答案1
得分: 1
你可以这样做:
要求 'csv'
文件1 = <<CSV1
用户ID,邮箱,出生日期
1,bob@bob.com,1998/12/1
2,alice@alice.com,2001/1/2
CSV1
文件2 = <<CSV2
用户ID,邮箱,姓名
1,bob@bob.com,bob
2,alice@alice.com,alice
CSV2
# 将行转换为哈希数组,
# 例如 [{ "用户ID" => "1", "邮箱" => "bob@bob.com", "出生日期" => "1998/12/1"},
# { "用户ID" => "2", "邮箱" => "alice@alice.com", "出生日期" => "2001/1/2"} ]
def csv_to_array(csv_string)
CSV.parse(csv_string, headers: true).map(&:to_h)
end
a1 = csv_to_array(文件1)
a2 = csv_to_array(文件2)
# 现在将两个数组合并,然后合并每个数组
puts a1.zip(a2).map{|a| a[0].merge(a[1])}.inspect
# => [{"用户ID" => "1", "邮箱" => "bob@bob.com", "出生日期" => "1998/12/1", "姓名" => "bob"},
# {"用户ID" => "2", "邮箱" => "alice@alice.com", "出生日期" => "2001/1/2", "姓名" => "alice"}]
英文:
you can do it like this:
require 'csv'
file1 = <<CSV1
user_id,email,dob
1,bob@bob.com,1998/12/1
2,alice@alice.com,2001/1/2
CSV1
file2 = <<CSV2
user_id,email,name
1,bob@bob.com,bob
2,alice@alice.com,alice
CSV2
# make an array of the rows as hashes,
# e.g. [ {"user_id"=>"1", "email"=>"bob@bob.com", "dob"=>"1998/12/1"},
# {"user_id"=>"2", "email"=>"alice@alice.com", "dob"=>"2001/1/2"} ]
def csv_to_array(csv_string)
CSV.parse(csv_string, headers: true).map(&:to_h)
end
a1 = csv_to_array(file1)
a2 = csv_to_array(file2)
# now zip the two arrays, then merge each
puts a1.zip(a2).map{|a| a[0].merge(a[1])}.inspect
# => [{"user_id"=>"1", "email"=>"bob@bob.com", "dob"=>"1998/12/1", "name"=>"bob"},
# {"user_id"=>"2", "email"=>"alice@alice.com", "dob"=>"2001/1/2", "name"=>"alice"}]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论