红宝石哈希转换为JSON仅示出了对象名(Ruby Hash converted to JSON on

2019-10-17 11:17发布

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

#<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一气呵成完全反应,而无需首先固定光电阵列?

Answer 1:

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

你有两个选择,要么变换的照片哈希像你一样,或猴子修补FlickRaw::Response与类to_json方法,在

class FlickRaw::Response
  def to_json
    to_hash
  end
end

这应该可以解决这个问题。



文章来源: Ruby Hash converted to JSON only shows object names