我使用net/http从Yahoo Placemaker API中提取一些json数据.收到响应后,我对响应执行JSON.parse.这给了我一个哈希,看起来像:

{"processingTime"=>"0.001493", "version"=>"1.4.0.526 build 111113", "documentLength"=>"25", "document"=>{"administrativeScope"=>{"woeId"=>"2503863", "type"=>"Town", "name"=>"Tampa, FL, US", "centroid"=>{"latitude"=>"27.9465", "longitude"=>"-82.4593"}}, "geographicScope"=>{"woeId"=>"2503863", "type"=>"Town", "name"=>"Tampa, FL, US", "centroid"=>{"latitude"=>"27.9465", "longitude"=>"-82.4593"}}, "localScopes"=>{"localScope"=>{"woeId"=>"2503863", "type"=>"Town", "name"=>"Tampa, FL, US (Town)", "centroid"=>{"latitude"=>"27.9465", "longitude"=>"-82.4593"}, "southWest"=>{"latitude"=>"27.8132", "longitude"=>"-82.6489"}, "northEast"=>{"latitude"=>"28.1714", "longitude"=>"-82.2539"}, "ancestors"=>[{"ancestor"=>{"woeId"=>"12587831", "type"=>"County", "name"=>"Hillsborough"}}, {"ancestor"=>{"woeId"=>"2347568", "type"=>"State", "name"=>"Florida"}}, {"ancestor"=>{"woeId"=>"23424977", "type"=>"Country", "name"=>"United States"}}]}}, "extents"=>{"center"=>{"latitude"=>"27.9465", "longitude"=>"-82.4593"}, "southWest"=>{"latitude"=>"27.8132", "longitude"=>"-82.6489"}, "northEast"=>{"latitude"=>"28.1714", "longitude"=>"-82.2539"}}, "placeDetails"=>{"placeId"=>"1", "place"=>{"woeId"=>"2503863", "type"=>"Town", "name"=>"Tampa, FL, US", "centroid"=>{"latitude"=>"27.9465", "longitude"=>"-82.4593"}}, "placeReferenceIds"=>"1", "matchType"=>"0", "weight"=>"1", "confidence"=>"8"}, "referenceList"=>{"reference"=>{"woeIds"=>"2503863", "placeReferenceId"=>"1", "placeIds"=>"1", "start"=>"15", "end"=>"20", "isPlaintextMarker"=>"1", "text"=>"Tampa", "type"=>"plaintext", "xpath"=>""}}}}

我可以通过做像jsonResponse['version']这样的事情来访问元素,但我不能做jsonResponse.version.这是为什么?

推荐答案

Hash的键没有点语法.OpenStruct是:

require 'ostruct'
hash = {:name => 'John'}
os = OpenStruct.new(hash)
p os.name #=> "John"

NOTE: Does not work with nested hashes.

Ruby相关问答推荐

Ruby:如何将两个返回值连接到一行中的两个字符串

整数除以负数

创建线程安全的临时文件名

ruby `encode': "\xC3" 从 ASCII-8BIT 到 UTF-8 (Encoding::UndefinedConversionError)

如何在不将换行符粘贴到字符串中的情况下使用puts添加额外的换行符?

什么是 Sinatra/Rack 的非常简单的身份验证方案

如何按长度对 Ruby 字符串数组进行排序?

Ruby数组中的`return`#map

如何从正在运行的脚本进入 IRB 提示符?

如何将参数传递给 array.map 快捷方式?

如果尚未定义,则设置 Ruby 变量

Vagrant - 如何拥有特定于主机平台的配置步骤

RSpec:如何测试文件操作和文件内容

array.include?多个值

在 ruby​​ 异常中捕获行号

Ruby,生成随机十六进制 colored颜色

如何在 Ruby 中取消定义类?

Ruby 方法to_sym有什么作用?

有条件的数组的第一个元素

如何在 Ruby 中重命名文件?