0

What I’m trying to do is loop through a hash and save certain key’s values to the database. This hash has nested keys, and I’m struggling to find a suitable way to loop through it.

First, I’m parsing the JSON of photos (from 500px API), and putting the response into terminal:

def index
  @photos = JSON.parse(get_access_token.get('/v1/photos/search?term=california').body)
  p @photos
  save @photos
end

The response I get in console is all okay and looks like this. (I’ve cut it down so it doesn’t take up too much room):

{
  "current_page": 1,
  "total_pages": 50,
  "total_items": 8263,
  "photos": [
    {
      "id": 4930535,
      "name": "Bike",
      "description": "",
      "times_viewed": 28,
      "rating": 27,
      "created_at": "2012-02-10T00:39:03-05:00"
    },
    {
      "id": 4930206,
      "name": "Rain",
      "description": "",
      "times_viewed": 1,
      "rating": 59.7,
      "created_at": "2012-02-10T00:04:09-05:00"
    },
    {
      "id": 4930202,
      "name": "California",
      "description": "",
      "times_viewed": 100,
      "rating": 58.2,
      "created_at": "2012-02-10T00:05:25-05:00"
    }
  ]
}

I’m then trying to loop through the photos and save the name, description and times_viewed to the db, using this save method.

def save photos

  photos.each do |photo|
    p = Photo.new(:name => photo["photos"]["name"], :description => photo["photos"]["description"], :times_viewed => photo["photos"]["times_viewed"])
    p.save
  end

end

The trouble is that the photos key is nested, and it throws this error in terminal:

TypeError (no implicit conversion of String into Integer):
  app/controllers/photos_controller.rb:18:in `[]'
  app/controllers/photos_controller.rb:18:in `block in save'
  app/controllers/photos_controller.rb:17:in `each'
  app/controllers/photos_controller.rb:17:in `save'
  app/controllers/photos_controller.rb:10:in `index'

2 Answers 2

3

Just take the photos array out of your json response and iterate over that. This way you only have one layer of hash keys to reference:

json_response['photos'].each do |photo|
  Photo.create name: photo['name'], description: photo['description'], 
    times_viewed: photo['times_viewed']
end
Sign up to request clarification or add additional context in comments.

Comments

0

photos["photos"] is an array so you need to specify the index before name. The implementation of your save method isn't completely clear, but I believe your parameters for the new method should have the form:

:name => photo["photos"][index]["name"]

You're getting a conversion error since the compiler is trying to convert name into an index.

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.