0

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

2 Answers 2

2

You can use JSON.parse to turn it into a hash

keywords = JSON.parse(response)["keywords"]
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your response. I ran response = RestClient.get "http://api.themoviedb.org/3/movie/8699/keywords", headers keywords = JSON.parse(response)["keywords"] keywords.each do |keyword| Keyword.create(name: keyword.name, tmdbid: keyword.id) end and get error NoMethodError: undefined method name for {"id"=>917, "name"=>"journalism"}:Hash
keywords is an array of Hash objects so you'll need to use it like so. keyword["name"] and keyword["id"] should work.
So, keywords.each do |keyword| Keyword.create(name: keyword["name"], tmdbid: keyword["id"]) end ??
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.