This lab today was one of the first times where I scratched my head and went, "HUH???" I think it was originally when we opend up the JSON file. It was ugly. In fact, Anil told us that it was one of the worst one's he had ever seen. Thanks, friend. Luckily, my group was amazing and we worked through the lab together. The most important take away from this lab?
Keep it DRY. Keep it simple. There is always an easier way to code something. Here is is, Voila! :)
#!/usr/bin/env ruby require 'open-uri' require 'json'
#original gist: https://gist.github.com/bridgpal/e032c851cebf6de1a968
url = "https://gist.github.com/bridgpal/e032c851cebf6de1a968/raw/820ef8ca253e9aaf986c010e235ef1141564fedc/products.json"
result = JSON.parse(open(url).read)
items = result["items"] #items array
***# 1. Print out the size of items returned***
puts "There are #{items.size} items in the .json file."
puts
***# 2. Print out items object where Items are from eBay***
count = 0
for item in items
product = item["product"]
author = product["author"]
if author["name"] =~ /eBay/
count += 1
puts product["title"]
end
end
puts "We have found #{count} items from eBay. They are listed above."
puts
***# What product is the 23rd item listed?***
#puts result["#{items[23]}"]
item_twentythird = items[22]["product"]["title"]
puts "The 23rd item returned in search is #{item_twentythird}"
***# Create an array of hashes. Each hash should include***
# product name product within >item
# description description is within >product > Items
# price price is in inventories > products >Items
# image_url image_url in link >images> product >Items
***# After creating that hash, iterate over that array and print each item on 1 line***
#inventories= product["inventories"]
#images=product["images"]
for item in items
product = item["product"]
hash = {
product: product["title"],
description: product["description"],
price: product["inventories"][0]["price"],
image_url: product["images"][0]["link"]
}
cameras = []
cameras << hash
cameras.each do |x|
puts "#{hash[:product]} - $#{hash[:price]} (#{hash[:description]}) "
end
end