How do I iterate over this JSON object?
Use JSON.parse to parse the response.
response = "{\"id\":\"a3adasfaf3\",\"url\":\"https://someurl/a3adasfaf3\",\"created\":\"2016-05-30T07:00:58Z\",\"modified\":\"2016-05-30T07:00:58Z\",\"files_hash\":\"cljhlk2j3l2kj34hlke18\",\"language\":\"ruby\",\"title\":\"Some weird hello world message\",\"public\":false,\"owner\":\"kljhlk2jh34lk2jh4l2kj3h4l2kj4h23l4kjh2l4k\",\"files\":[{\"name\":\"Some-weird-hello-world-message.rb\",\"content\":\"puts \\\"Some weird hello world message.\\\"\\r\\n\"}]}"
require 'json'
JSON.parse response
# output:
# {"id"=>"a3adasfaf3", "url"=>"https://someurl/a3adasfaf3", "created"=>"2016-05-30T07:00:58Z", "modified"=>"2016-05-30T07:00:58Z", "files_hash"=>"cljhlk2j3l2kj34hlke18", "language"=>"ruby", "title"=>"Some weird hello world message", "public"=>false, "owner"=>"kljhlk2jh34lk2jh4l2kj3h4l2kj4h23l4kjh2l4k", "files"=>[{"name"=>"Some-weird-hello-world-message.rb", "content"=>"puts \"Some weird hello world message.\"\r\n"}]}
response["name"] # => a3adasfaf3
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 and retrive just the values from a json object with ruby
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.
Ruby - iterate over parsed JSON
You're trying to iterate over data
, which is a hash, not a list. You need to get the children array from your JSON object by data['data']['children']
require "net/http"
require "uri"
require "json"
uri = URI.parse("http://www.reddit.com/user/brain_poop/comments/.json")
response = Net::HTTP.get_response(uri)
data = JSON.parse(response.body)
data['data']['children'].each do |child|
puts child['data']['body']
end
given a json object, how to iterate through the object in rails
Symbols and strings are different things (except when you're using HashWithIndifferentAccess), you should be using a string as a key:
JSON.parse(list_items_open).each do |item|
Rails.logger.info item['id']
end
This is a hash with an 'id'
key:
{ "id" => 193 }
This is a hash with an :id
key:
{ :id => 193 }
How to iterate over this Json data in rails?
Four problems:
- you are not parsing the response body with
JSON.parse
- you are using a constant name (starting with capital letter) as a variable name (
@Response
), you shouldn't. - unnecessary
puts
on iteration. - The value of
data
is not an array, but rather another hash. So you should iterate over it as key/value pairs.
Solution:
@response = JSON.parse(HTTParty.get(your_url).body)
@response["data"].each do |key, value|
puts key
puts value
end
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 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
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
Related Topics
Update Field Through Link_To in Rails
Can't Dup Nilclass on Association Methods
How to Read a Clients Windows Login Name Using Ruby on Rails
Uploading New Products with Multiple Variant Options
Bootstrap Modal in Ruby on Rails Not Working
Using Poltergeist with a Proxy
How to Download File from Google Drive API with Service Account
How to Get Repeated Elements from Ruby Array
How to 'Join' an Array Adding to the Beginning of the Resulting String the First Character to Join
Parsing Uris That Have Curly Braces, Uri::Invalidurierror: Bad Uri(Is Not Uri)
How to Understand the #Dup and #Clone Operate on Objects Which Referencing Other Objects
Gitlab: Invocation of Gitlab-Shell
How to Convert an Octal Number to Decimal in Ruby
Rails 404 Error for Stylesheet or JavaScript Files
Elegant Way to Only Show Records If They Exist in Rails Erb
Get List Timeline by Using Twitter Gem
Testing HTML5 File Upload with Capybara/Selenium Webdriver - Ruby