简体   繁体   English

CSV 未将正确格式的 JSON 导入数据库

[英]CSV not importing JSON with correct format into database

Just like the title says, here is my code:就像标题所说,这是我的代码:

require 'json'
def import_csv
  path = Rails.root.join('folder1', 'folder2', 'file.csv')
  counter = 0
  puts "inserts on table started..."
  CSV.foreach(path, headers: true) do |row|
    next if row.to_hash['deleted_at'] != nil
    counter += 1
    puts row.to_json #shows correct format
    someModel = someModel.new(row.to_hash) #imports incorrect format of json with backslash in db
    #someModel = someModel.new(row.to_json) #ArgumentError: When assigning attributes, you must pass a hash as an argument.
    someModel.skip_callbacks = true
    someModel.save!
    end
  puts "#{counter} inserts on table apps complete"
end
import_csv

I can not import the CSV File in the correct format.我无法以正确的格式导入 CSV 文件。 The import works, but the structure is wrong.导入有效,但结构错误。

EXPECTED预期的

{"data":{"someData":72}}

GETTING得到

"{\"data\":{\"someData\":72}}"

How can I import it with the correct JSON format?如何使用正确的 JSON 格式导入它?

If all headers are correct as of the column names of the model Maybe you can try:如果 model 的列名中的所有标题都正确,也许您可以尝试:

JSON.parse(row.to_json)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM