2

I have a JSON array structured like this:

{"data":[{"Chris":[{"long":10,"lat":19}]},{"Scott":[{"long":9,"lat":18}]}]}

I am then reading from the array in ruby, and I have started to iterate through the JSON array like so:

objArray = JSON.parse(File.open('public/test.json').read);
sections = objArray["data"]

sections.each do |subsections|
        subsections.each do |supersub|
            supersub.each do |obj| 

                #Check if variable Usrname is equal to a name in the JSON array
            end
        end 
    end

As the comment in the loop says, I need to compare the variable Usrname to the names in the JSON array i.e "Chris" and "Scott" to see if Usrname matches any of them. How is this done?

1 Answer 1

2
username = 'Chris'
sections.each do |user_coords|
  user_coords.each do |user, coords|
    if user == username
      # Do stuff here...
      puts "OK: #{coords}"
    end
  end
end

# OK: [{"long"=>10, "lat"=>19}]
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, this worked. Do you know how I can then edit the coords of the name?
You can access them via user_coords[name] - that is the array of hashes of "lat/long" per user.
SO do I do it like this: rb_hash[user_coords[Usrname]] << {lng: Lng.to_i, lat: Lat.to_i}

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.