jqualls
jqualls

Reputation: 1503

Import JSON into Heroku Rails app then store in database

I have a Rails 3.2 Application that is hosted on Heroku. I would like to try and avoid manually entering all of the data for each new record. Is their an easy way for me to get my rails app to look at a JSON file like this (except MUCH LARGER) and parse that information into the database?

[   {
    "name": "Sierra Mist – Small Cup",
    "wwpplus": "5",
    "ssize": "451g",
    "calories": "190",
    "tfat": "0",
    "protein": "0",
    "fiber": "0",
    "carbs": "50",
    "restaurant_id": "12"
},
{
    "name": "Vanilla Shake regular",
    "wwpplus": "13",
    "ssize": "425g",
    "calories": "480",
    "tfat": "15",
    "protein": "14",
    "fiber": "0",
    "carbs": "74",
    "restaurant_id": "12"
},
{
    "name": "Vanilla Shake small",
    "wwpplus": "11",
    "ssize": "340g",
    "calories": "380",
    "tfat": "12",
    "protein": "11",
    "fiber": "0",
    "carbs": "60",
    "restaurant_id": "12"
}]

Upvotes: 2

Views: 2151

Answers (1)

Nick Colgan
Nick Colgan

Reputation: 5508

You could parse it in your db/seeds.rb file:

records = JSON.parse(File.read('path/to/file.json'))
records.each do |record|
  ModelName.create!(record)
end

Then heroku run rake db:seed

Upvotes: 11

Related Questions