【问题标题】:Iterate JSON with Ruby and insert to MySQL db用 Ruby 迭代 JSON 并插入 MySQL 数据库
【发布时间】:2015-03-14 22:12:20
【问题描述】:

我正在访问这样的开放 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}]  

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

  • 名称(不在区域块中,而是在“tbone”中)
  • 阻塞时间
  • 总点数
  • 区域数组中的所有 ID

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

在做

puts data["name"]

给出一个类似的错误

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

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

请?

【问题讨论】:

    标签: mysql ruby arrays json parsing


    【解决方案1】:

    所以你有:

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

    【讨论】:

    • 谢谢.. 不过对我没用。这样做result = JSON.parse(response.body) result[0].slice("name", "blocktime", "totalPoints", "zones") 但是得到这个错误 ``
      ': undefined method slice' for #&lt;Hash:0x000000011cfd80&gt; (NoMethodError)
    • 啊,不用担心。我要戒掉红宝石了。回到安全的 php 旧世界:D
    猜你喜欢
    • 2018-11-17
    • 2015-07-08
    • 1970-01-01
    • 2013-03-25
    • 1970-01-01
    • 2019-04-01
    • 2014-04-26
    • 1970-01-01
    • 2022-08-14
    相关资源
    最近更新 更多