jsonrubycsvparsingfastercsv

JSON Array to CSV via FasterCSV


I have a JSON array in the following format.

[{"Name":"Ann","Gender":"Female","Age":"20"},{"Name":"John","Gender":"Male","Age":"22"}]

I want to convert this into following CSV format without printing the "Key" and also i want it to print only the Name value and Age value. for e.g. Ann,20 John,22

I have tried with following code.

#!//usr/bin/env ruby
require "rubygems"
require 'fastercsv'
require 'json'

csv_string = FasterCSV.generate({}) do |csv|
   JSON.parse(File.open("test").read).each do |hash|
    csv << hash
  end
end

puts csv_string

test contains the json array which i'm try to parse.


Solution

  • Your JSON format is invalid. Valid json format is:

    [{"Name":"Ann","Gender":"Female","Age":"20"},{"Name":"John","Gender":"Male","Age":"22"}]
    

    Try this:

    require "rubygems"
    require 'fastercsv'
    require 'json'
    
    csv_string = FasterCSV.generate({}) do |csv|
      JSON.parse(File.open("test").read).each do |hash|
        csv << [hash["Name"], hash["Age"]]
      end
    end
    
    puts csv_string