user1094976
user1094976

Reputation:

How to get key from json file format..?

I'm using json gem in ruby..,My ruby code is here..,

require 'json'

json = JSON.generate [1, 2, [{"pi" => 3.141}, {"integer" => 1234567890}], {"subject" => "Mathematics"}, {"Float"=> 1.324343}, {"number"=> 232132435}]
generator = JSON.parse json
puts generator[2][1]

My key-value pair is working fine.But, I'm trying to print only the key not an value from index[2] such as either an "integer" or "pi". Is it possible..?

Upvotes: 1

Views: 4574

Answers (1)

Aliaksei Kliuchnikau
Aliaksei Kliuchnikau

Reputation: 13739

In your case generator[2][1] is a Hash {"integer"=>1234567890}. In order to get all keys from hash you can use Hash#keys method, and then take first (as far as it is the only key in the hash)

generator[2][1].keys.first # => "integer"

You can learn more about Hash methods in this documentation.

Your data structure at generator[2] looks strange, maybe you better use a single Hash for such casese:

{"pi" => 3.141, "integer" => 1234567890} # etc...

Upvotes: 1

Related Questions