How to access hash converted JSON data by hacking into ruby?

Here is an example from the crack documentation:

json = '{"posts":[{"title":"Foobar"}, {"title":"Another"}]}'
Crack::JSON.parse(json)
=> {"posts"=>[{"title"=>"Foobar"}, {"title"=>"Another"}]}

But how do I access the data in a hash?

I tried the following:

array = Crack::JSON.parse(json)
array["posts"]

array ["posts"] shows all the values, but I tried array ["posts"] ["title"] and it did not work.

Here is what I am trying to analyze as an example:

{"companies"=>[{"city"=>"San Mateo", "name"=>"Jigsaw", "address"=>"777 Mariners Island Blvd Ste 400", "zip"=>"94404-5059", "country"=>"USA", "companyId"=>4427170, "activeContacts"=>168, "graveyarded"=>false, "state"=>"CA"}], "totalHits"=>1}

I want to access individual items under companies ... like city and name.

+3
source share
1 answer

Like this?

hash = {
  "companies" => [
    {
      "city"           => "San Mateo", 
      "name"           => "Jigsaw", 
      "address"        => "777 Mariners Island Blvd Ste 400", 
      "zip"            => "94404-5059", 
      "country"        => "USA", 
      "companyId"      => 4427170, 
      "activeContacts" => 168, 
      "graveyarded"    => false, 
      "state"          => "CA"
    }
  ], 
  "totalHits" => 1
}

hash['companies'].each{ |i| 
  puts "city => #{i['city']}"
  puts "name => #{i['name']}" 
}
# >> city => San Mateo
# >> name => Jigsaw

hash['companies'][0]['city'] # => "San Mateo"
hash['companies'][0]['name'] # => "Jigsaw"

The problem is that you did not account for the array that it points to companies.

+7
source

Source: https://habr.com/ru/post/1782106/


All Articles