0

I'm acceessing an open JSON API like this

require 'net/http'
require 'rubygems'
require 'json'
require 'uri'
require 'pp'

url = "http://api.turfgame.com/v4/users"
uri = URI.parse(url)

data = [{"name" => "tbone"}]


headers = {"Content-Type" => "application/json"}

http = Net::HTTP.new(uri.host,uri.port)

response = http.post(uri.path,data.to_json,headers)

This gives a JSON ouput like this

[{"region"=>{"id"=>141, "name"=>"Stockholm"}, "medals"=>[34, 53, 12, 5, 46], "pointsPerHour"=>95, "blocktime"=>24, "zones"=>[275, 42460, 35956, 31926, 24247, 31722, 1097, 26104, 6072, 24283, 289, 325, 22199, 37740, 22198, 37743, 37074, 22845, 22201, 22846, 7477, 7310], "country"=>"se", "id"=>95195, "rank"=>24, "name"=>"tbone", "uniqueZonesTaken"=>178, "taken"=>1170, "points"=>41693, "place"=>377, "totalPoints"=>176654}]  

What I want to do is to grab some of the tags:

  • name (not in the region block but "tbone")
  • blocktime
  • totalPoints
  • all the IDs from the zone-array

and insert into a mysql table. But I don't get how to iterate the JSON object and get the stuff I want.

doing

puts data["name"]

gives an error like

./headerTest.rb:28:in `[]': can't convert String into Integer (TypeError)
        from ./headerTest.rb:28:in `<main>'

And I get that it's because there's two name tags but at different depth but i don't get how to accees either one specifically.

Please?

1 Answer 1

1

So you have:

result = [{"region"=>{"id"=>141, "name"=>"Stockholm"}, "medals"=>[34, 53, 12, 5, 46], "pointsPerHour"=>95, "blocktime"=>24, "zones"=>[275, 42460, 35956, 31926, 24247, 31722, 1097, 26104, 6072, 24283, 289, 325, 22199, 37740, 22198, 37743, 37074, 22845, 22201, 22846, 7477, 7310], "country"=>"se", "id"=>95195, "rank"=>24, "name"=>"tbone", "uniqueZonesTaken"=>178, "taken"=>1170, "points"=>41693, "place"=>377, "totalPoints"=>176654}]  

This is an array with one value. To obtain those values you desire do:

result[0].slice("name", "blocktime", "totalPoints", "zones")

# this returns =>  {"name"=>"tbone", "blocktime"=>24, "totalPoints"=>176654, "zones"=>[275, 42460, 35956, 31926, 24247, 31722, 1097, 26104, 6072, 24283, 289, 325, 22199, 37740, 22198, 37743, 37074, 22845, 22201, 22846, 7477, 7310]}
Sign up to request clarification or add additional context in comments.

2 Comments

thanks.. didn't work for me though. Did this result = JSON.parse(response.body) result[0].slice("name", "blocktime", "totalPoints", "zones") But get this error ``<main>': undefined method slice' for #<Hash:0x000000011cfd80> (NoMethodError)
ah, no worries. I'm quitting ruby. heading back to the safe old world of php :D

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.