Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a particular key value from json in ruby

[  "KEY1":{"SUB_KEY1" : "VALUE1","SUB_KEY2" : "VALUE2"}, "KEY2":{"SUB_KEY1" : "VALUE1","SUB_KEY2" : "VALUE2"} ] 

The above is my json object which is coming as a response.

How do I get SUB_KEY1 of KEY1 and SUB_KEY1 of KEY2 in Ruby on Rails?

Thank you.

like image 761
Anand Soni Avatar asked Mar 18 '11 05:03

Anand Soni


People also ask

Can a value be the key in JSON?

Keys must be strings, and values must be a valid JSON data type: string. number.

Is JSON a key-value store?

A JSON database makes it possible to store data as JSON and provide it to applications in other forms. For example, it can operate as an in-memory key-value store for applications that just need quick and easy access. Or, indexing and querying can make JSON data appear as a table.


2 Answers

You need to parse the JSON object into a ruby hash. Assuming your JSON response is called res:

require 'json' obj = JSON.parse(res)  sv1 = obj['KEY1']['SUB_KEY1'] 

etc.

like image 110
Jacob Avatar answered Oct 11 '22 08:10

Jacob


parsed_json = ActiveSupport::JSON.decode(your_json_string)

will parse your string as

  [{"KEY1"=>{"SUB_KEY1"=>"VALUE1", "SUB_KEY2"=>"VALUE2"}}, {"KEY2"=>{"SUB_KEY1"=>"VALUE1", "SUB_KEY2"=>"VALUE2"}}] 

You should be able to access it using something like parsed_json[1]["KEY2"]["SUB_KEY1"]

like image 40
Rishav Rastogi Avatar answered Oct 11 '22 10:10

Rishav Rastogi