[ "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.
Keys must be strings, and values must be a valid JSON data type: string. number.
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.
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.
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With