1

我有一个FlickRaw想要转换为 JSON 的 Ruby 响应。这是其结构的一部分:

#<FlickRaw::Response:0x7fbd11088678
    @h = {
               "id" => "72157628092176654",
          "primary" => "6332013810",
            "owner" => "8623220@N02",
        "ownername" => "The Library of Congress",
            "photo" => [
            [ 0] #<FlickRaw::Response:0x7fbd1106a628
                @h = {
                           "id" => "6332007340",
                       "secret" => "4d92733d70",
                       "server" => "6217",
                         "farm" => 7,
                        "title" => "Woodrow Wilson, Twenty-Eighth President of the United States (LOC)",
                    "isprimary" => "0"
                },
                attr_reader :flickr_type = "photo"
            >,

要将其转换为 JSON,我想简单地采用response.to_hash.to_json,但这会导致以下结果:

=> "{"id":"72157628092176654",
"primary":"6332013810",
"owner":"8623220@N02",
"ownername":"The Library of Congress",
"photo":["#<FlickRaw::Response:0x007fbd1106a628>","#<FlickRaw::Response:0x007fbd110704d8>","#<FlickRaw::Response:0x007fbd11079c40
...

如您所见,它仅输出#<FlickRaw::Response>对象而不是实际内容。所以,它只是停止在那里递归。我如何让它实际输出类似于我从awesome_print上面得到的输出的东西,其中也显示了各个照片字段?

我尝试了以下方法,这让我得到了照片数组的正确表示:

photos.photo.map { |h| h.to_hash  }.to_json

但这似乎相当复杂。有没有更简单的方法可以一次性将完整的响应格式化为 JSON,而无需先修复照片数组?

4

1 回答 1

3

显然该类型FlickRaw::Response没有默认的 JSON 表示。

您有两个选择,要么像您一样将照片转换为哈希,要么使用以下方法对FlickRaw::Response类进行猴子补丁to_json

class FlickRaw::Response
  def to_json
    to_hash
  end
end

这应该可以解决问题。

于 2012-12-05T17:53:17.023 回答