Convert csv to json in ruby

2019-08-07 16:57发布

CSV

id,modifier1_name,modifier2_price,modifier2_name,modifier2_price,modifier2_status
1,'Small',10,'Large',20,'YYY'
2,'Small',20,'Large',30,'YYY'

JSON

[
{
 id: 1,
 modifier: [
   {name: 'Small', price: 10},
   {name: 'Large', price: 20, status: 'YYY'}]
},
{
 id: 2,
 modifier: [
   {name: 'Small', price: 20},
   {name: 'Large', price: 30, status: 'YYY'}],
}
]

How to convert CSV to Json in this case when modifiers can be different ?

标签: ruby json csv
2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-08-07 17:39
require 'csv'
require 'json'

CSV.open('filename.csv', :headers => true).map { |x| x.to_h }.to_json
查看更多
The star\"
3楼-- · 2019-08-07 17:49

You will need to map the modifiers yourself, as there is no built-in method to map hash values into an array from your logic:

JSON.pretty_generate(CSV.open('filename.csv', headers: true).map do |row|
  modifier = {}
  row.each do |k, v|
    if k =~ /modifier(.)_(.*)$/
      (modifier[$1] ||= {})[$2] = v
    end
  end
  { id: row['id'],
    modifier: modifier.sort_by { |k, v| k }.map {|k, v| v }
  }
end)

For the file*

id,modifier1_name,modifier1_price,modifier2_name,modifier2_price,modifier2_status
1,Small,10,Large,20,YYY
2,Small,20,Large,30,YYY

*I made some changes to the file you show, since it will not give you the required result - you state modifier2_price twice, for example

You will get:

[
  {
    "id": "1",
    "modifier": [
      {
        "name": "Small",
        "price": "10"
      },
      {

        "name": "Large",
        "price": "20",
        "status": "YYY"
      }
    ]
  },
  {
    "id": "2",
    "modifier": [
      {
        "name": "Small",
        "price": "20"
      },
      {
        "name": "Large",
        "price": "30",
        "status": "YYY"
      }
    ]
  }
]
查看更多
登录 后发表回答