如何在Ruby中查询基本API

分享于 

3分钟阅读

Rails

  繁體

JSON是最广泛使用的,我们开始吧!


require "open-uri" # Allows us to send GET requests and receive the response
require "json" # Allows us to parse the reponse into a JSON object/hash

现在我们可以


response = open("").read
=> {"forms":[{"url":"http://pokeapi.co/api/v2/pokemon-form/65/","name":"alakazam"}],"abilities":[{"slot":3,"is_hidden":true,"ability":{"url":"http://pokeapi.co/api/v2/ability/98/","name":"magic-guard"}},{"slot":2,"is_hidden":false,"ability":{"url":"http://pokeapi.co/api/v2/ability/39/","name":"inner-focus"}},{"slot":1,"is_hidden":false,"ability"...}

现在我们有了一个JSON字符串,可以解析成JSON对象;


json = JSON.parse(response)
=> {"forms"=>
 [{"url"=>"", "name"=>"alakazam"}],
 "abilities"=>
 [{"slot"=>3,
 "is_hidden"=>true,
 "ability"=>
 {"url"=>"", "name"=>"magic-guard"}},
 {"slot"=>2,
 "is_hidden"=>false,
 "ability"=>
 {"url"=>"", "name"=>"inner-focus"}},
 {"slot"=>1,
 "is_hidden"=>false,
 "ability"=>
 {"url"=>"", "name"=>"synchronize"}}],
 "stats"=>
 [{"stat"=>{"url"=>"", "name"=>"speed"},
 "effort"=>0,
 "base_stat"=>120},
 {"stat"=>
 {"url"=>"", "name"=>"special-defense"},
 "effort"=>0,
 "base_stat"=>95},...

json.class
=> Hash

现在,我们可以像对待其他ruby对象一样对待它了,比方说,我想检索alakazam的所有动作,可以


json["moves"].collect {|move| move["move"]["name"]}
=> 
["mega-punch",
 "fire-punch",
 "ice-punch",
 "thunder-punch",
 "mega-kick",
 "headbutt",
 "body-slam",
 "take-down",
 "double-edge",
 "disable",
 "psybeam",
 "hyper-beam",
 "submission",
 "counter",
 "seismic-toss",
 "thunder-wave",
 "dig",
 "toxic",
 "confusion",
 "psychic", # THIS is probably the strongest move of alakazam. ALWAYS use your pp-ups on this!

API  Basic  
相关文章