Pro_grammer
Pro_grammer

Reputation: 356

Regex/Gsub removing all nested double quotes instead of just the outer ones

I want to import the following CSV into rails db:

"[{""id"":""actions"",""name"":""app"",""description""}]"

After importing, I always get:

"{\"id\":\"actions\",\"name\":\"app\",\"description\"]}"

I want the import to looks like this:

[{"id":,"actions":,"name":,"description",...}]"

I tried using .gsub!(/"/,'') but this returns:

"[{id:actions,name:actions,description:}]"

The issue is that all the quote marks have been removed so its just id insted of "id"

My code is:

def import_app_version
  path = Rails.root.join('db', 'csv_export', 'app_versions.csv')
  counter = 0
  puts "Inserts on table app_versions started..."


  CSV.foreach(path, headers: true) do |row|
    next if row.to_hash['modules'] == nil
    row.to_hash['modules'].gsub!(/"/,'')
    next if row.to_hash['deleted_at'] != nil
    counter += 1
    AppVersion.skip_callbacks = true
    AppVersion.create!(row.to_hash)
  end
  AppVersion.skip_callbacks = false
  puts "#{counter} inserts on table app_versions complete"
end

What is the right way to do this so that the import works correctly and the data is imported as it's meant to be?

I have been searching for half a day, and found so many answers but they all end up removing all of the double quotes as displayed above.

Or even better would be, if someone knew a way to import csv with JSON content the right way.

Upvotes: 0

Views: 175

Answers (1)

Danny_ds
Danny_ds

Reputation: 11406

Do not use replace, or do not try to remove quotes manually.

"[{""id"":""actions"",""name"":""app"",""description""}]"

If you read the above data with a csv parser/reader (maybe with a parameter 'quoted fields') all should be fine.

The surrounding quotes will be removed and the inside quotes will be unescaped to one double quote.

Upvotes: 2

Related Questions