Iterate JSON with Ruby and get a key,value in an array
json = JSON.parse(your_json)
values = json.map { |_, v| { v[:PATH] => v[:ARTIFACTS].split(',') } }
You'll get the nice hash
{
'/tmp/pruebaAlvaro' => ['example1.jar', 'another_one.jar', ...],
'/tmp/pruebaAlvaro2' => [...]
}
And, you can iterate over it:
values.each do |path, artifacts|
artifacts.each do |artifact|
puts path
puts artifact
end
puts
end
You'll get the same output, which you provided in the question
How to iterate through an JSON array to get a value of a key?
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)
how to iterate through json result in ruby on rails?
You can use map to transform every element of a collection
def get_results
results = getJsonData();
results.map { |item| item.merge("year" => 2000) }
end
In this case I'm adding a key "year"
to your hashes with value 2000
, it depends what you want to do
How to iterate through a JSON array in Rails
params["Schedule"]
gets an hash, not an array. So your block will have a key (the day as a name) and an array
params["Schedule"].each do |day_name, day_schedule|
# to do
end
Iterate JSON array and find all matched values
You are almost there. Use =~
instead of ==
iy ou want to match a string with a regexp:
@json_array.contacts_obtained.select do |i|
i['identity-profiles'][0]['identities'][0]['value'] =~ /@example.com/
end
Best way to iterate over JSON array with variable keys with jq/bash
One more variation
jq '[
.Results[]
| .FixedVersion //= ""
| .VulnerabilityID //= ""
| .InstalledVersion //= ""
]' file.json
How do you iterate over and retrieve values from a hash with arrays?
instagram.rb:23:in `[]': can't convert String into Integer (TypeError)
You're getting this error because in puts item["id"]
, item
is an Array, not a Hash, so Ruby tries to convert what you put between []
into an integer index, but it can't because it's a string ("id"
).
This arises from the fact that json_output.body
is a Hash. Take a second look at the example JSON response in the documentation:
{ "data" : [
{ "type" : "image",
// ...
"id" : "22699663",
"location" : null
},
// ...
]
}
This whole structure becomes a single Hash with one key, "data"
, so when you call @tags.each
you're actually calling Hash#each
, and since "data"
's value is an Array when you call item["id"]
you're calling Array#[]
with the wrong kind of parameter.
Long story short, what you actually want to do is probably this:
@tags = JSON.parse( json_output.body )[ "data" ]
..then @tags
will be the Array you want instead of a Hash and you can iterate over its members like you wanted:
@tags.each do |item|
puts item["id"]
end
Iterate over JSON Array in Rails5
Since 'k' is a hash, you need to access k['name'] and k['price'] to extract price and name.
Also when you use .each on an array, you normally only declare one block argument (You have two, k and v ).
You normally write 2 block arguments for Hashes (and lots of other Enumerable methods), which is possibly what you thought you were iterating over, but
@plaqy['products']
is an array
Iterating through a array of hashes in Ruby (parsed JSON)
Your code seems to lack i
variable (index) here, but actually you don't need it, since you can always use map
function to achieve idiomatic Ruby code:
require "json"
response = '{
"results": [
{
"zip": "08225",
"city": "Northfield",
"county": "Atlantic",
"state": "NJ",
"distance": "0.0"
},
{
"zip": "08221",
"city": "Linwood",
"county": "Atlantic",
"state": "NJ",
"distance": "1.8"
}
]
}'
parsed_response = JSON.parse(response)
zipcode_array = parsed_response["results"].map { |address| address["zip"] }
Related Topics
Getting a Rogue Iteration from My .Each Loop
How to Use String Methods on Utf-8 Characters
How to Create Two Routes in One Block in Grape
How to Transform the Utf8 Chars to Iso8859-1
Defined' and 'Unless' Not Working as Expected
How to HTML_Escape Text Data in a Sinatra App
How to Reduce the Quality of an Uploading Image Using Paperclip
Uml Sequence Diagram - How to Represent Method Arguments That Instantiate Objects
Using Class Instance Variable for Mutex in Ruby
Hardcoded "Require 'Debug'" Can't Find the Sourcefile
Rails Search Query Associated Model
Rails Object Based Permission/Authorization Engine
Ruby ".Downcase! " and "Downcase" Confusion
Ruby Popen3 -- How to Repeatedly Write to Stdin & Read Stdout Without Re-Opening Process
Omission of Curly Braces for a Hash in an Array
Generate Full Url to JavaScript in Rails (Similar to JavaScript_Path, But Url)