【问题标题】:generating json from csv file in Ruby在 Ruby 中从 csv 文件生成 json
【发布时间】:2015-05-17 17:57:53
【问题描述】:

我需要读取包含大量数据的 CSV 文件并将其转换为 JSON 对象。我已经编写了这段代码,但是生成的 JSON 对象有一些错误,并且不符合我的预期。

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

【问题讨论】:

  • 错误是什么?可以发一下吗?
  • 它得到了修复..谢谢

标签: ruby json csv


【解决方案1】:

我认为这段代码会对你有所帮助(我从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

【讨论】:

  • 这很顺利..你也可以指导我阅读一些关于如何使用类(类似于 java)和正则表达式(ruby 中的 RegEx)在 ruby​​ 中编写程序的书籍
  • 我喜欢 Russ Olsen 的 Eloquent Ruby
  • 如果对您有帮助,请检查答案。 :P
  • 是的,有一张支票,上面有一个 0 和一个向上行和一个向下行。如果你点击那里会很棒;-)
猜你喜欢
  • 2018-06-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-19
  • 1970-01-01
  • 1970-01-01
  • 2016-11-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多