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)
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With