2013-12-02 2 views
0

Я пытаюсь научиться разбирать элементы JSON с Ruby и ударить по блоку.Сверните в JSON с Ruby

В приведенном ниже фрагменте кода элемент категории возвращает данные, но как мне получить доступ к его дочерним элементам? Например, в ответе 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 

ответ

1
json = JSON.parse(str) 
json['entries'].each { |entry| 
    entry['categories'].each { |category| 
    puts category['label'] 
    } 
} 
+0

Удивительный! Благодарю. –

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' 
Смежные вопросы