我正在尝试学习如何使用Ruby解析JSON元素并且遇到了障碍。
在下面的代码片段中,categories项会返回数据但是如何访问它的子元素?例如,在JSON响应中,我想要仅获得类别的标签值。
JSON响应
{
"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
答案 0 :(得分:1)
json = JSON.parse(str)
json['entries'].each { |entry|
entry['categories'].each { |category|
puts category['label']
}
}
答案 1 :(得分:0)
str = '{ "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 " } ] } ] }'
obj = JSON.parse(str)
obj['entries'][0]['categories'].map { |c| c['label'] }
最后一行给出了3元素的字符串数组
'Photo'
'NHL hockey'
'Professional hockey'