I'm using net/http
to pull in some json data from the Yahoo Placemaker API. After receiving the response I am performing JSON.parse
on the response. This gives me a hash that looks like:
{"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"=>""}}}}
I am able to access elements by doing things like jsonResponse['version']
but I am not able to do jsonResponse.version
. Why is this?
If it's in Rspec stubs will work too.
Because
Hash
doesn't have aversion
method.Ruby hashes don't work like this natively, but the HashDot gem would work for this.
HashDot allows dot notation syntax use on hashes. It also works on json strings that have been re-parsed with
JSON.parse
.Why not, you can do this via metaprogramming
OpenStruct will work well for a pure hash, but for hashes with embeded arrays or other hashes, the dot syntax will choke. I came across this solution, which works well without loading in another gem: https://coderwall.com/p/74rajw/convert-a-complex-nested-hash-to-an-object basic steps are:
you can now access all objects in mystr using dot syntax.
That is a JavaScript feature, not a Ruby feature. In Ruby, to use a "dot syntax", the object would need to respond to those methods. Ruby hashes use the
#[](key)
method to access elements.