Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 524
N. Hess Avatar asked Jan 30 '17 23:01

N. Hess


People also ask

How do I get JSON data in Ruby on Rails?

You can use open-uri to fetch the data from the URL to then be parsed by JSON like so... open returns a StringIO object which responds to read returning the JSON data. JSON. load turns the data into a hash to be used.

What is JSON parse in rails?

One way to use rails to parse json in a scalable and effective manner is to create a class that parses the JSON response and manages the data from the json fields using the object. The problem with this approach is we need to maintain the class and have to be clear on which fields are included in the JSON.


1 Answers

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
like image 149
Hardik Gondaliya Avatar answered Oct 25 '22 05:10

Hardik Gondaliya