ruby on rails - How to iterate through an JSON array to get a value of a key? -
i have response string looked this:
"[{\"id\":\"blahbla23sdlkjrwer2345\",\"name\":\"bar\"},{\"id\":\"aselrjdsfsomething\",\"name\":\"foo\"}]"
then used json.parse(response_above)
:
json_parse = json.parse(response_above) =>[{"id"=>"blahbla23sdlkjrwer2345", "name"=>"bar"}, {"id"=>"aselrjdsfsomething", "name"=>"foo"}]
from here want names , set them array. figured out how names don't how build new array.
to "foo" or "bar" can this:
json_parse[0].fetch("name") => "bar" json_parse[1].fetch("name") => "foo"
i don't how iterate through array build new array json response like:
new_array = ["foo", "bar"]
the json response can dynamic, may have 2 elements, other times can have 10 elements. can't hard code value in. need find way iterate through array "name" key getting each of values.
like many ruby answers there few ways 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
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 subject well. created array 1000000 hashes in them , called 3 methods above on it. #collect
appears fastest though tests vary bit run run.
user scheme 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)
ruby-on-rails ruby arrays json
No comments:
Post a Comment