如何迭代此JSON对象?

时间:2016-05-30 07:21:21

标签: ruby-on-rails ruby json

这是一个在HTTP POST请求中作为response返回的对象:

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

对于奖励积分,我想要的只是存储在每个属性中的实际值(即实际id(只是一个字符串)和url(这是一个典型的URL)。所以如果你包括我如何访问该属性,然后在那将是非常棒的同时清理它。

2 个答案:

答案 0 :(得分:5)

使用 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

答案 1 :(得分: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]parsed_hash[:url]

访问ID和网址