2016-05-30 96 views
-2

這是在HTTP POST請求返回的response對象:如何迭代這個JSON對象?

res.body 
=> "{\"id\":\"a3adasfaf3\",\"url\":\"https://someurl/a3adasfaf3\",\"created\":\"2016-05-30T07:00:58Z\",\"modified\":\"2016-05-30T07:00:58Z\",\"files_hash\":\"cljhlk2j3l2kj34hlke18\",\"language\":\"ruby\",\"title\":\"Some weird hello world message\",\"public\":false,\"owner\":\"kljhlk2jh34lk2jh4l2kj3h4l2kj4h23l4kjh2l4k\",\"files\":[{\"name\":\"Some-weird-hello-world-message.rb\",\"content\":\"puts \\\"Some weird hello world message.\\\"\\r\\n\"}]}" 

我試圖拉出來,並把這一response的各種屬性。例如,至少在idurl

我該怎麼做?

爲了記錄,我使用Ruby的NET/HTTP std lib發送POST請求並取回此響應。

編輯1

獎勵積分,我要的是一個url(這是一個典型的URL)存儲在每個屬性(即實際id(這僅僅是一個字符串的實際值)。所以,如果你包括我怎麼可能都訪問該屬性,然後在同一時間,將是真棒消毒它。

+2

嘗試'JSON.parse(RES)' –

+0

嘿,你可以使用'Json.parse(RES)[ 「ID」]'的ID和URL'Json.parse(res)[「url」]' –

+0

@VishalJAIN我現在意識到我可以做到這一點。謝謝。 – marcamillion

回答

3

使用JSON.parse解析響應。

response = "{\"id\":\"a3adasfaf3\",\"url\":\"https://someurl/a3adasfaf3\",\"created\":\"2016-05-30T07:00:58Z\",\"modified\":\"2016-05-30T07:00:58Z\",\"files_hash\":\"cljhlk2j3l2kj34hlke18\",\"language\":\"ruby\",\"title\":\"Some weird hello world message\",\"public\":false,\"owner\":\"kljhlk2jh34lk2jh4l2kj3h4l2kj4h23l4kjh2l4k\",\"files\":[{\"name\":\"Some-weird-hello-world-message.rb\",\"content\":\"puts \\\"Some weird hello world message.\\\"\\r\\n\"}]}" 

require 'json' 

JSON.parse response 
# output: 
# {"id"=>"a3adasfaf3", "url"=>"https://someurl/a3adasfaf3", "created"=>"2016-05-30T07:00:58Z", "modified"=>"2016-05-30T07:00:58Z", "files_hash"=>"cljhlk2j3l2kj34hlke18", "language"=>"ruby", "title"=>"Some weird hello world message", "public"=>false, "owner"=>"kljhlk2jh34lk2jh4l2kj3h4l2kj4h23l4kjh2l4k", "files"=>[{"name"=>"Some-weird-hello-world-message.rb", "content"=>"puts \"Some weird hello world message.\"\r\n"}]} 

response["name"] # => a3adasfaf3 
+0

我喜歡你要去的地方,你可以添加一個代碼示例,我會接受它。 – marcamillion

+0

這是完美的。謝謝! – marcamillion

+0

在'eval(response)'上使用'JSON.parse'有什麼好處? – marcamillion

2

您需要JSON.parse 實例解析它:

parsed_hash = JSON.parse res.body 

結果:

{ 
      "id" => "a3adasfaf3", 
      "url" => "https://someurl/a3adasfaf3", 
     "created" => "2016-05-30T07:00:58Z", 
     "modified" => "2016-05-30T07:00:58Z", 
    "files_hash" => "cljhlk2j3l2kj34hlke18", 
     "language" => "ruby", 
     "title" => "Some weird hello world message", 
     "public" => false, 
     "owner" => "kljhlk2jh34lk2jh4l2kj3h4l2kj4h23l4kjh2l4k", 
     "files" => [ 
     [0] { 
       "name" => "Some-weird-hello-world-message.rb", 
      "content" => "puts \"Some weird hello world message.\"\r\n" 
     } 
    ] 
} 

要訪問ID:

parsed_hash['id'] 

要訪問的網址:

parsed_hash['url'] 

想要通過符號訪問它?

parsed_hash = JSON.parse(res.body).symbolize_keys 

您現在可以通過parsed_hash[:id]訪問ID和URL和parsed_hash[:url]

+0

在'eval(response)'上使用'JSON.parse'有什麼好處? – marcamillion

+0

謝謝你。 – marcamillion