Reputation: 1303
I have a response string that looked something like this:
"[{\"id\":\"blahbla23sdlkjrwer2345\",\"name\":\"bar\"},{\"id\":\"aselrjdsfsomething\",\"name\":\"foo\"}]"
Then I used JSON.parse(response_above)
:
json_parse = JSON.parse(response_above)
=>[{"id"=>"blahbla23sdlkjrwer2345", "name"=>"bar"},
{"id"=>"aselrjdsfsomething", "name"=>"foo"}]
From here I only want the names and put them into an array. I figured out how to get the names but don't how to build it into a new array.
To get just "foo" or "bar" I can do this:
json_parse[0].fetch("name")
=> "bar"
json_parse[1].fetch("name")
=> "foo"
I don't how to iterate through the array to build a new array from the JSON response like:
new_array = ["foo", "bar"]
The JSON response can be dynamic, sometimes I may only have 2 elements, other times I can have 10 elements. I can't hard code a value in. I need to find a way to iterate through that array for the "name" key getting each of the values.
Upvotes: 1
Views: 4307
Reputation: 15977
Like many Ruby answers there are a few ways to do it:
Setup:
[1] pry(main)> require 'json'
=> true
[2] pry(main)> json = JSON.parse("[{\"id\":\"blahbla23sdlkjrwer2345\",\"name\":\"bar\"},{\"id\":\"aselrjdsfsomething\",\"name\":\"foo\"}]")
using #inject
:
[5] pry(main)> json.inject([]) { |arr, entry| arr << entry['name'] ; arr }
=> ["bar", "foo"]
using #map
as Nerian pointed out:
[6] pry(main)> json.map { |entry| entry['name'] }
=> ["bar", "foo"]
using #collect
:
[7] pry(main)> json.collect { |entry| entry['name'] }
=> ["bar", "foo"]
Some interesting benchmarks on the subject as well. I created an array with a million hashes in them and called the 3 methods above on it. #collect
appears to be the fastest though the tests vary a bit from run to run.
user system total real
map 0.300000 0.020000 0.320000 ( 0.325673)
collect 0.260000 0.030000 0.290000 ( 0.285001)
inject 0.430000 0.010000 0.440000 ( 0.446080)
Upvotes: 3
Reputation: 16197
Here is how:
2.1.3 :006 > require 'json'
=> true
2.1.3 :007 > json = JSON.parse("[{\"id\":\"blahbla23sdlkjrwer2345\",\"name\":\"bar\"},{\"id\":\"aselrjdsfsomething\",\"name\":\"foo\"}]")
=> [{"id"=>"blahbla23sdlkjrwer2345", "name"=>"bar"}, {"id"=>"aselrjdsfsomething", "name"=>"foo"}]
2.1.3 :008 > json.map { |entry| entry['name'] }
=> ["bar", "foo"]
Upvotes: 6