Reputation: 231
I am using an API for movies, for the most part I use a gem, but in order to get certain information, I have to use RestClient.get
methods.
response = RestClient.get "http://api.themoviedb.org/3/movie/8699/keywords", headers
puts response
If I run this code, it returns this JSON "extract"
{"id":8699,"keywords":[{"id":917,"name":"journalism"},{"id":4411,"name":"sexism"},{"id":6198,"name":"ladder"},{"id":8531,"name":"panda"},{"id":18290,"name":"1970s"},{"id":18298,"name":"tv show in film"},{"id":41390,"name":"mustache"},{"id":165288,"name":"misogynist"},{"id":167241,"name":"newsroom"},{"id":167250,"name":"teleprompter"},{"id":167252,"name":"what happened to epilogue"},{"id":167254,"name":"gang warfare"},{"id":167256,"name":"multiple cameos"},{"id":179430,"name":"aftercreditsstinger"},{"id":179431,"name":"duringcreditsstinger"},{"id":185281,"name":"news spoof"}]}
Now what I need to do is be able to do is turn the above into a rails readable piece of code, so that I can then put it into a database.
More specifically, I would like to take the above information and be able to execute it as such
keywords.each do |keyword|
Keyword.create(name: keyword.name, tmdbid: keyword.id)
end
So that it creates a new Keyword based on each keyword and its name & id based on the JSON File
Upvotes: 0
Views: 89
Reputation: 3574
It will be faster if you create all keywords at once by first create correct array of values to be saved. Here is what I will do
keywords = JSON.parse(response)["keywords"].map do |k|
{ name: k["name"], tmdbid: k["id"] }
end
Keyword.create(keywords) #one SQL statement only
Regards
Upvotes: 0
Reputation: 938
You can use JSON.parse
to turn it into a hash
keywords = JSON.parse(response)["keywords"]
Upvotes: 2