Home > Mobile >  how to iterate and retrive just the values from a json object with ruby
how to iterate and retrive just the values from a json object with ruby

Time:02-24

Say I have a simple json object like

{"a" :"1", "b":"2", "c":"3"}

In ruby, how can I iterate through that object just so I can get the values 1 2 and 3.

CodePudding user response:

assuming you have the object as a string.

require 'json'
json_obj = '{"a" :"1", "b":"2", "c":"3"}'
values = JSON.parse(json_obj).values

will provide you with the array

["1", "2", "3"]

JSON.parse , parses the json string into a ruby object, in this case an instance of a Hash. The Hash class has a method values which returns an array containing the values or each hash entry.

CodePudding user response:

Here's a pure ruby approach that can be used for parsing a simple json string like that:

First convert your string to an array:

json_str = '{"a" :"1", "b":"2", "c":"3"}'

json_arr = json_str.scan(/"(.*?)"/).map(&:join)
#=>  ["a", "1", "b", "2", "c", "3"]

You could stop there and just iterate through that array to grab every second element using something like each_slice(2).map(&:last)or you could finish the conversion to a hash. There are several ways to do this, but here's one using Hash[] along with the splat operator:

json_hash = Hash[*json_arr]
#=>  {"a"=>"1", "b"=>"2", "c"=>"3"}

You can then simply access the values:

json_hash.values
#=>  ["1", "2", "3"]

All in one line:

Hash[*'{"a\'a\'" :"1", "b":"2", "c":"3"}'.scan(/"(.*?)"/).map(&:join)].values
  • Related