2017-01-30 64 views
1

我對此還是很新的 - 請輕鬆點我吧!將JSON數據導入Rails

我有一個包含此信息的JSON文件restaurant_list.json

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

我有相同的列名,試圖使這個數據導入容易Rails的創建Restaurant模型。我嘗試了其他堆棧溢出答案中使用的各種serializeJSON.parse()方法,但沒有成功。

如何將這些數據導入到我的Rails數據庫中?

(注:我使用Rails的標準SQLite,讓我的數據庫)

回答

1

你可以這樣做在軌控制檯或創建rake任務:

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

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

感謝您的答覆。我在rails控制檯中運行了第一行,並得到了這個錯誤:'JSON :: ParserError:784:',' –

+1

意外標記找出JSON錯誤。我不得不改變文件的格式。之後,你的答案完美:) –