用 Ruby 迭代 JSON 并插入到 MySQL db

Iterate JSON with Ruby and insert to MySQL db

我正在访问一个打开的 JSON API 像这样

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)

这给出了这样的 JSON 输出

[{"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}]  

我想做的是抓取一些标签:

并插入 mysql table。但是我不知道如何迭代 JSON 对象并获得我想要的东西。

正在做

puts data["name"]

给出类似

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

我知道这是因为有两个名称标签,但深度不同,但我不知道如何具体访问其中一个。

请问?

所以你有:

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}]  

这是一个只有一个值的数组。要获得您想要的值,请执行以下操作:

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]}