N. Hess
N. Hess

Reputation: 83

Import JSON data to Rails

I am still pretty new to this--go easy on me please!

I have a JSON file restaurant_list.json that contains this information:

[{
  "objectID": 116272,
  "food_type": "Steak",
  "stars_count": 4.2,
  "reviews_count": 204,
  "neighborhood": "Pepper Pike",
  "_geoloc": {"lat": 41.153419, "lng": -81.864608},
   ...},
etc.
etc.
]

I created a Restaurant model in Rails that has identical column names to try and make this data import easy. I have tried various serialize and JSON.parse() methods used in other Stack Overflow answers with no success.

How do I get this data into my Rails database?

(Note: I am using the Rails standard SQLite for my database)

Upvotes: 8

Views: 6656

Answers (1)

Hardik Gondaliya
Hardik Gondaliya

Reputation: 326

You can do like this in rails console or create rake task:

restaurant_list = JSON.parse(File.read('restaurant_list.json'))

restaurant_list.each do |restaurant|
  Restaurant.create(restaurant.to_h)
end

Upvotes: 14

Related Questions