0

I am trying to write a simple JSON parser. I am getting my JSON string from odata.org.

I tried to access the elements of the parsed JSON string using the technique listed in the second answer in "Parsing a JSON string in ruby". You'll see that there are a bunch of "name" keys inside the "value" key that I want to access and print out.

This is what I currently have:

require 'net/http'
require 'uri'
require 'rubygems'
require 'json'

def open(url)
  Net::HTTP.get(URI.parse(url))
end

page_content = open('http://services.odata.org/Northwind/Northwind.svc/?$format=json')
parsed = JSON.parse(page_content)

parsed["value"]["name"].each do |name|
p name["name"]
end

I have printed out the parsed string and it seems to be a properly parsed JSON representation of the string. If you do not want to get the JSON string from the website, here it is.

{"odata.metadata":"http://services.odata.org/Northwind/Northwind.svc/$metadata","value":[{"name":"Categories","url":"Categories"},{"name":"CustomerDemographics","url":"CustomerDemographics"},{"name":"Customers","url":"Customers"},{"name":"Employees","url":"Employees"},{"name":"Order_Details","url":"Order_Details"},{"name":"Orders","url":"Orders"},{"name":"Products","url":"Products"},{"name":"Regions","url":"Regions"},{"name":"Shippers","url":"Shippers"},{"name":"Suppliers","url":"Suppliers"},{"name":"Territories","url":"Territories"},{"name":"Alphabetical_list_of_products","url":"Alphabetical_list_of_products"},{"name":"Category_Sales_for_1997","url":"Category_Sales_for_1997"},{"name":"Current_Product_Lists","url":"Current_Product_Lists"},{"name":"Customer_and_Suppliers_by_Cities","url":"Customer_and_Suppliers_by_Cities"},{"name":"Invoices","url":"Invoices"},{"name":"Order_Details_Extendeds","url":"Order_Details_Extendeds"},{"name":"Order_Subtotals","url":"Order_Subtotals"},{"name":"Orders_Qries","url":"Orders_Qries"},{"name":"Product_Sales_for_1997","url":"Product_Sales_for_1997"},{"name":"Products_Above_Average_Prices","url":"Products_Above_Average_Prices"},{"name":"Products_by_Categories","url":"Products_by_Categories"},{"name":"Sales_by_Categories","url":"Sales_by_Categories"},{"name":"Sales_Totals_by_Amounts","url":"Sales_Totals_by_Amounts"},{"name":"Summary_of_Sales_by_Quarters","url":"Summary_of_Sales_by_Quarters"},{"name":"Summary_of_Sales_by_Years","url":"Summary_of_Sales_by_Years"}]}

Thanks in advance for all of your help. Hopefully it's just an easy fix.

Community
  • 1
  • 1
kirie
  • 375
  • 1
  • 3
  • 15

1 Answers1

1

You've almost got it. "value" contains an array which is what you want to loop through. Each element of that array contains a name which is what you want to access.

parsed["value"].each do |record|
  p record["name"]
end
Anthony
  • 15,435
  • 4
  • 39
  • 69