使用多个键解析JSON字符串

时间:2015-02-26 17:59:43

标签: ruby json rubygems

我正在尝试编写一个简单的JSON解析器。我从odata.org获取了我的JSON字符串。

我尝试使用“Parsing a JSON string in ruby”中第二个答案中列出的技术访问已解析的JSON字符串的元素。你会看到我想要访问和打印的“值”键中有一堆“名称”键。

这就是我目前所拥有的:

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

我打印出解析后的字符串,它似乎是字符串的正确解析的JSON表示。如果您不想从网站获取JSON字符串,请点击此处。

{"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"}]}

提前感谢您的所有帮助。希望这只是一个简单的解决方案。

1 个答案:

答案 0 :(得分:1)

你几乎得到了它。 "value"包含一个数组,这是您想要循环的数组。该数组的每个元素都包含一个您想要访问的名称。

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