0

I need to read a CSV file containing huge data and transform it into a JSON Object. I have written this code but the JSON Objects generated are having some error in it and is not according to my expectations.

def readFromFile(fileName)

        jsonFile = File.open('some.json','w')

         CSV.foreach(fileName,:headers => true, :header_converters => :symbol) do |row| 
         $jsonData['Email'] = {
              :subject => row[0],
              :body => row[1],
              :fromName => row[2],
              :fromEmail => row[3],
              :toName => row[5],
              :toEmail => row[6]
          }
          # puts "data is #{jsonData[jsonData.length-1]}"

          jsonFile.write(JSON.pretty_generate($jsonData));

         # CSV.parse(row).to_json
         # @jsonFile.write(JSON.pretty_generate(@jsonData));
       #   csv = CSV.new(fileName, :headers => true, :header_converters => :symbol, :converters => :all)
        #  csv.to_a.map {|row| row.to_hash }
    end
2
  • What is the error? Could you post it. Commented Mar 15, 2015 at 16:22
  • it got fixed..thanks Commented Mar 15, 2015 at 17:02

1 Answer 1

1

I think this code will help you ( I get it from http://jasonheppler.org/2014/07/12/parsing-csv-to-json/ ):

def readFromFile(fileName)
  def is_int(str)
    # Check if a string should be an integer
    return !!(str =~ /^[-+]?[1-9]([0-9]*)?$/)
  end

  lines = CSV.open(filename).readlines
  keys = lines.delete lines.first

  File.open('some.json', "w") do |f|
    data = lines.map do |values|
      is_int(values) ? values.to_i : values.to_s
      Hash[keys.zip(values)]
    end
    f.puts JSON.pretty_generate(data)
  end
end
Sign up to request clarification or add additional context in comments.

4 Comments

This worked smoothly..also could you guide me to some books which is starightforward in how to write programs in ruby using classes(similar to java) and regular expressions(RegEx in ruby)
I like Eloquent Ruby by Russ Olsen
Please check the answer if it helps u. :P
Yeah, there is a check with a 0 and one up row and one down row. Will be great if you click there ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.