1

我正在使用返回复杂哈希的 API (zillow)。样本结果是

{"xmlns:xsi"=>"http://www.w3.org/2001/XMLSchema-instance", 
 "xsi:schemaLocation"=>"http://www.zillow.com/static/xsd/SearchResults.xsd http://www.zillowstatic.com/vstatic/5985ee4/static/xsd/SearchResults.xsd", 
 "xmlns:SearchResults"=>"http://www.zillow.com/static/xsd/SearchResults.xsd", "request"=>[{"address"=>["305 Vinton St"], "citystatezip"=>["Melrose, MA 02176"]}],
 "message"=>[{"text"=>["Request successfully processed"], "code"=>["0"]}],
 "response"=>[{"results"=>[{"result"=>[{"zpid"=>["56291382"], "links"=>[{"homedetails"=>["http://www.zillow.com/homedetails/305-Vinton-St-Melrose-MA-02176/56291382_zpid/"], 
 "graphsanddata"=>["http://www.zillow.com/homedetails/305-Vinton-St-Melrose-MA-02176/56291382_zpid/#charts-and-data"], "mapthishome"=>["http://www.zillow.com/homes/56291382_zpid/"], 
 "comparables"=>["http://www.zillow.com/homes/comps/56291382_zpid/"]}], "address"=>[{"street"=>["305 Vinton St"], "zipcode"=>["02176"], "city"=>["Melrose"], "state"=>["MA"], "latitude"=>["42.466805"], 
 "longitude"=>["-71.072515"]}], "zestimate"=>[{"amount"=>[{"currency"=>"USD", "content"=>"562170"}], "last-updated"=>["06/01/2014"], "oneWeekChange"=>[{"deprecated"=>"true"}], "valueChange"=>[{"duration"=>"30", "currency"=>"USD", "content"=>"42749"}], "valuationRange"=>[{"low"=>[{"currency"=>"USD", 
 "content"=>"534062"}], "high"=>[{"currency"=>"USD", "content"=>"590278"}]}], "percentile"=>["0"]}], "localRealEstate"=>[{"region"=>[{"id"=>"23017", "type"=>"city", 
 "name"=>"Melrose", "links"=>[{"overview"=>["http://www.zillow.com/local-info/MA-Melrose/r_23017/"], "forSaleByOwner"=>["http://www.zillow.com/melrose-ma/fsbo/"],
 "forSale"=>["http://www.zillow.com/melrose-ma/"]}]}]}]}]}]}]}

我可以使用以下方法提取特定值:

result = result.to_hash

p result["response"][0]["results"][0]["result"][0]["zestimate"][0]["amount"][0]["content"]

必须以这种方式指定每个元素的索引似乎很奇怪。有没有更简单的方法来获取命名值?

4

2 回答 2

2

看起来应该将其解析为 XML。根据Zillow API Docs,它默认返回 XML。显然,“to_hash”能够把它变成一个哈希(虽然,一个非常丑陋的),但你真的想通过这种方式向上游游泳。我建议在开始时按预期使用它(xml),然后可能稍后将其解析为更易于使用的格式(如 JSON/Hash 结构)。

Nokogiri非常擅长解析 XML!您可以使用 xpath 语法从 dom 甚至 css 选择器中获取元素。

例如,要在每个结果中获取“内容”数组:

response = #get xml response from zillow
results = Nokogiri::XML(response).remove_namespaces!
#using css
content_array = results.css("result content")
#same thing using xpath:
content_array = results.xpath("//result//content")

如果您只想要第一个结果中的内容,您可以将其作为快捷方式:

content = results.at_css("result content").content
于 2014-06-04T17:46:16.237 回答
0

由于它确实是将 XML 转储到 JSON 中,因此您可以使用JSONPath来查询 JSON

于 2014-06-04T17:30:49.623 回答