Ruby deep hash looping? - ruby

I have a large nested hash in the form below. I need to loop through and pull out the name and url of each repository, but I can't seem to do that. Any suggestions?
Code snippet:
repo_json = get_touched_repos()
repo_hash = JSON.parse(repo_json)
puts repo_hash.class
puts repo_hash['repositories'][0]['name']
The hash:
{
"repositories": [
{
"type": "repo",
"username": "...",
"name": "....",
"owner": "...",
"homepage": "",
"description": "description",
"language": "Java",
"watchers": 2,
"followers": 2,
"forks": 1,
"size":
"open_issues": 0,
"score": 1.0,
"has_downloads": true,
"has_issues": true,
"has_wiki": true,
"fork": false,
"private": false,
"url": "http://my.domain.com/repo/name",
"created": "2012-07-02T17:47:54Z",
"created_at": "2012-07-02T17:47:54Z",
"pushed_at": "2014-03-20T20:09:38Z",
"pushed": "2014-03-20T20:09:38Z"
},
{....}
]
}

You can use Array#each method to do this
repo_hash['repositories'].each do |repo|
puts repo['name']
puts repo['url']
end

To get the names and the URLs in a hash:
name_url_pairs = repo_hash['repositories'].collect do |repo|
{ name: repo['name'], url: repo['url] }
end
Update: Returning a small hash with several extracted values.
Another approach to index by name:
name_hash = Hash[
repo_hash['repositories'].collect do |repo|
[ repo['name'], repo['url'] ]
end
]

Related

Add new items to multidimensional Ruby hash in loop

Migrating my code to Ruby stuck on the updating this hash with new items inside the multidimensional hash>customers>image>
bannerhash = {
"stooge": "larry",
"toppings": [],
"customers": [
{
"id": 1,
"alt": "Image seo text",
"image": {
"label": "gid:///28663588552955",
"image": "https://cdn.doma.com/s/files/1/0611/2064/3323/files/yellow-pillow-bedside-table_2000x.jpg?v=1637223489"
},
"mainsize": 100
},
{
"id": 2,
"alt": "Image seo text",
"image": {
"label": "gid:///28663588487419",
"image": "https://cdn.doma.com/s/files/1/0611/2064/3323/files/bed-side-table_2000x.jpg?v=1637223489"
},
"mainsize": 100
},
{
"id": 3,
"alt": "image",
"themeposition": "388506648827/posA",
"image": {
"label": "gid:///28663588585723",
"image": "https://cdn.doma.com/s/files/1/0611/2064/3323/files/sunlight-creeps-through-a-bright-living-room_2000x.jpg?v=1637223489"
},
"mainsize": 87
},
{
"id": 4,
"alt": "short width",
"themeposition": "home",
"mainsize": 70,
"image": {
"label": "gid:///28663588454651",
"image": "https://cdn.doma.com/s/files/1/0611/2064/3323/files/modern-and-stylish-design_2000x.jpg?v=1637223489"
},
"quickcss": "#import url(\'https://fonts.googleapis.com/css2?family=Comic+Neue:wght#300&display=swap\');\n.wrapper-4 .--description {font-family: \'Comic Neue\', cursive; }"
}
]
}
Want to update in the loop and the add the "newitem" key with value inside the "image" like
{
"stooge": "larry",
"toppings": [],
"customers": [
{
"id": 1,
"alt": "Image seo text",
"image": {
"label": "gid:///28663588552955",
"image": "https://cdn.doma.com/s/files/1/0611/2064/3323/files/yellow-pillow-bedside-table_2000x.jpg?v=1637223489",
"newitem": "https://cdn.doma.com/s/files/1/0611/2064/3323/files/yellow-pillow-bedside-table_3300x.jpg?v=1637223489"
},
"mainsize": 100
},
{
"id": 2,
"alt": "Image seo text",
"image": {
"label": "gid:///28663588487419",
"image": "https://cdn.doma.com/s/files/1/0611/2064/3323/files/bed-side-table_2000x.jpg?v=1637223489",
"newitem": "https://cdn.doma.com/s/files/1/0611/2064/3323/files/bed-side-table_3300x.jpg?v=1637223489"
},
"mainsize": 100
}
]
}
My workaround code where I am stuck on how ruby update hash inside the each loop. First I catch the inner hash with the "customers" key and know the index and value however stuck on how to add "newitem" inside the "customers" "image" hash
if bannerhash.has_key?(:customers)
puts "found"
bannerhash.each_with_index do |(key, value), index|
if key == :customers
puts "index: #{index} | key: #{key} | value: #{value}"
# STACK Here bannerhash[key].each
end
end
else
puts "banners not found"
end
This seems pretty straightforward. No need to loop over all of the key/value pairs looking for :customers when we can access it directly.
if bannerhash.has_key?(:customers)
bannerhash[:customers].each { |h|
h[:image][:newitem] = "https://cdn.doma.com/s/files/1/0611/2064/3323/files/yellow-pillow-bedside- table_3300x.jpg?v=1637223489"
}
else
puts "banners not found"
end

Sorting an array of objects based on object property

I have an array like so:
[
{
"name": "aabb",
"commit": {
"id": "1",
"message": "aabb ",
"committed_date": "2018-04-04T15:11:04.000+05:30",
"committer_name": "ak",
"committer_email": "ak#ak.in"
},
"protected": false
},
{
"name": "aacc",
"commit": {
"id": "2",
"message": "aacc ",
"committed_date": "2018-02-04T15:11:04.000+05:30",
"committer_name": "ak",
"committer_email": "ak#ak.in"
},
"protected": false
},
{
"name": "aadd",
"commit": {
"id": "3",
"message": "aadd ",
"committed_date": "2018-04-01T15:11:04.000+05:30",
"committer_name": "ak",
"committer_email": "ak#ak.in"
},
"protected": false
}
]
I need to sort this array based on committed_date. How do I do that?
Do I have to loop and write a custom sorting function or does Ruby offers something out-of-box?
Using sort_by
array.sort_by {|obj| obj.attribute}
Or more concise
array.sort_by(&:attribute)
In your case
array.sort_by {|obj| obj[:commit][:committed_date]}

How can I access elements of a JSON return from a Stripe api call?

I am using ruby and sinatra. After a Stripe API call, I want to access an element, from a JSON return, and put it into my database.
The ruby code is:
require 'sinatra'
require 'stripe'
require 'pg'
require 'sequel'
get '/save_customer' do
customer = Stripe::Customer.retrieve("cus_6EfJSbJ8gCTxxx")
puts customer
last4 = customer["sources"]["data"]["last4"]
DB[:stripe_customers].insert(:user_id=>user_id, :email=>email, :stripe_customer_id=>customer_id, :stripe_customer_card=> last4)
end
The JSON (taken from the API docs, not my return) is as follows:
{
"object": "customer",
"created": 1431570089,
"id": "cus_6EfJSbJ8gCTxxx",
"livemode": false,
"description": "Example customer",
"email": null,
"delinquent": false,
"metadata": {
},
"subscriptions": {
"object": "list",
"total_count": 0,
"has_more": false,
"url": "/v1/customers/cus_6EfJSbJ8gCTMrd/subscriptions",
"data": [
]
},
"discount": null,
"account_balance": 0,
"currency": "usd",
"sources": {
"object": "list",
"total_count": 1,
"has_more": false,
"url": "/v1/customers/cus_6EfJSbJ8gCTMrd/sources",
"data": [
{
"id": "card_162ByRBVd5ndD62KfaONcG4G",
"object": "card",
"last4": "4242",
"brand": "Visa",
"funding": "credit",
"exp_month": 12,
"exp_year": 2018,
"country": "US",
"name": null,
"address_line1": null,
"address_line2": null,
"address_city": null,
"address_state": null,
"address_zip": "123456",
"address_country": null,
"cvc_check": "pass",
"address_line1_check": null,
"address_zip_check": "pass",
"dynamic_last4": null,
"metadata": {
},
"customer": "cus_6EfJSbJ8gCTxxx"
}
I have tried:
last4 = customer[:data][:sources][:last4]
and with "" as above.
The error message has varied, currently TypeError - no implicit conversion of String into Integer. I assume this is because I have not extracted the element I need correctly, or it could mean that the api call did not work but I assume that it did.
Try this:
last4 = customer["sources"]["data"][0]["last4"]

Transferring JSON Data into an array using ruby

This is my JSON code
{
"jobs": [
{
"id": 1,
"title": "Software Developer",
"applicants": [
{
"id": 1,
"name": "Rich Hickey",
"tags": ["clojure", "java", "immutability", "datomic", "transducers"]
},
{
"id": 2,
"name": "Guido van Rossum",
"tags": ["python", "google", "bdfl", "drop-box"]
}
]
},
{
"id": 2,
"title": "Software Architect",
"applicants": [
{
"id": 42,
"name": "Rob Pike",
"tags": ["plan-9", "TUPE", "go", "google", "sawzall"]
},
{
"id": 2,
"name": "Guido van Rossum",
"tags": ["python", "google", "bdfl", "drop-box"]
},
{
"id": 1337,
"name": "Jeffrey Dean",
"tags": ["spanner", "BigTable", "MapReduce", "deep learning", "massive clusters"]
}
]
}
]
}
I want to put the list of "Jobs" in an array using ruby.
I have the following code so far.
require 'json'
file = File.read(filepath)
data_hash = JSON.parse(file)
How do I iterate on the data_hash and chose what information I want and place it in an array?
You can use Array#each because data_hash['jobs'] contains an array of jobs:
data_hash['jobs'].each {|job| ... }
Like this,
arr = Array.new
data_hash.each { |job|
arr.insert(job['name'])
}
use Array#map for shorter code
data_hash['jobs'].map do |job|
# Do whatever you want with the job here
properties = %w(title applicants)
job.select{ |key| properties.include?(key) }
end

Parsing out multiple API JSON response parameters

I'm getting a JSON response back from an API, however the response has several key parameters all called 'jacket' with different values. I am able to parse out the first key but I don't get the rest of the values. Here is some of the code, I might be approaching this the wrong way:
parsed_list = JSON.parse(get_response.body)
orig = parsed_list["_links"]["stuff"]["orig"]
serv = parsed_list["_links"]["stuff"]["serv"]
puts orig.first["jacket"]
puts serv.first["jacket"]
=> 123456789
=> 987654321
This is what the JSON response looks like before I parse it out and set it "parsed_list"
"_links": {
"self": {
"href": "url"
},
"stuff": {
"href": "url",
"orig": [
{
"jacket": "123456789",
"Id": "x",
"selected": true,
}
],
"serv": [
{
"jacket": "987654321",
"Id": "xx",
"selected": false,
},
{
"jacket": "0000000001",
"Id": "xx",
"selected": false,
},
{
"jacket": "1111111110",
"Id": "xx",
"selected": false,
}
]
}
}
}
I need to be able to extract all of the "jacket" values.
The data's right there, you just need to get it:
serv.collect do |entry|
entry['jacket']
end

Resources