Convert .json to .csv in ruby

前端 未结 7 1485
心在旅途
心在旅途 2020-12-24 09:42

I want to convert .json file into .csv file using ruby. Pleases help me to do this.

Also propose any tool to achieve this.

7条回答
  •  情话喂你
    2020-12-24 09:49

    This is handle headers & nested json.

    require 'csv'
    require 'json'
    
    @headers = []
    file = File.open('file.json')
    JSON.parse(file.read).each do |h|
      h.keys.each do |key|
        @headers << key
      end
    end
    
    uniq_headers = @headers.uniq
    file = File.open('file.json')
    finalrow = []
    
    JSON.parse(file.read).each do |h|
      final = {}
      @headers.each do |key2|
        final[key2] = h[key2]
      end
    
      finalrow << final
    end
    
    CSV.open('output.csv' , 'w') do |csv|
      csv << uniq_headers
      finalrow.each do |deal|
        csv << deal.values
      end
    end
    

提交回复
热议问题