使用Ruby深入研究JSON
我试图学习如何用Ruby解析JSON元素,但遇到了一个障碍 在下面的代码片段中,categories项返回数据,但如何访问它的子项?例如,在JSON响应中,我只想得到类别的标签值 JSON响应使用Ruby深入研究JSON,ruby,json,Ruby,Json,我试图学习如何用Ruby解析JSON元素,但遇到了一个障碍 在下面的代码片段中,categories项返回数据,但如何访问它的子项?例如,在JSON响应中,我只想得到类别的标签值 JSON响应 { "title": "test", "updated": "2013-12-02T01:46:51.282Z", "startIndex": 1, "itemsPerPage": 1, "entries": [ { "id"
{
"title": "test",
"updated": "2013-12-02T01:46:51.282Z",
"startIndex": 1,
"itemsPerPage": 1,
"entries": [
{
"id": "fooURL",
"title": "fooTitle",
"updated": "2013-12-01T04:15:16Z",
"published": "2013-11-30T21:49:58Z",
"categories": [
{
"term": "c706572879441004880dba7Fa5283c3e",
"scheme": "http://fooURL.com/id/",
"label": "Photo"
},
{
"term": "20DFCC087E4E10048925D0913B2D075C",
"scheme": "http://fooURL.com/id/",
"label": "NHL hockey "
},
{
"term": "20DE22407E4E100488FBD0913B2D075C",
"scheme": "http://fooURL.com/id/",
"label": "Professional hockey "
}
]
}
]
}
require "rubygems"
require "json"
require "net/http"
require "uri"
uri = URI.parse("http://fooURL.com/v2/search/photo?q=Giroux&count=2&apikey=mykey")
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new(uri.request_uri, {'Accept' => 'application/json'})
response = http.request(request)
result = JSON.parse(response.body[3..-1].force_encoding("UTF-8"))[ "entries" ]
result.each do |item|
puts item["id"]
puts item["title"]
puts item["updated"]
puts item['categories']
end
代码
{
"title": "test",
"updated": "2013-12-02T01:46:51.282Z",
"startIndex": 1,
"itemsPerPage": 1,
"entries": [
{
"id": "fooURL",
"title": "fooTitle",
"updated": "2013-12-01T04:15:16Z",
"published": "2013-11-30T21:49:58Z",
"categories": [
{
"term": "c706572879441004880dba7Fa5283c3e",
"scheme": "http://fooURL.com/id/",
"label": "Photo"
},
{
"term": "20DFCC087E4E10048925D0913B2D075C",
"scheme": "http://fooURL.com/id/",
"label": "NHL hockey "
},
{
"term": "20DE22407E4E100488FBD0913B2D075C",
"scheme": "http://fooURL.com/id/",
"label": "Professional hockey "
}
]
}
]
}
require "rubygems"
require "json"
require "net/http"
require "uri"
uri = URI.parse("http://fooURL.com/v2/search/photo?q=Giroux&count=2&apikey=mykey")
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new(uri.request_uri, {'Accept' => 'application/json'})
response = http.request(request)
result = JSON.parse(response.body[3..-1].force_encoding("UTF-8"))[ "entries" ]
result.each do |item|
puts item["id"]
puts item["title"]
puts item["updated"]
puts item['categories']
end
最后几行给出了字符串的3元素数组
'Photo'
'NHL hockey'
'Professional hockey'