1

I have a Ruby FlickRaw response that I want to convert to JSON. Here's part of its structure:

#<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"
            >,

To convert it to JSON, I thought of simply taking response.to_hash.to_json, but this results in the following:

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

As you can see, it merely outputs #<FlickRaw::Response> objects instead of the actual contents. So, it simply stops recursing there. How do I get it to actually output something like the output I got from awesome_print above, where the individual photo fields are shown as well?

I've tried the following, which gets me the correct representation for the photo array:

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

But that seems rather complicated. Any easier way to format the complete response as JSON in one go, without fixing the photo array first?

4

1 に答える 1

3

どうやら、型FlickRaw::Responseにはデフォルトの JSON 表現がありません。

2 つのオプションがあります。写真をハッシュに変換するか、次のようなメソッドでFlickRaw::Responseクラスをモンキー パッチします。to_json

class FlickRaw::Response
  def to_json
    to_hash
  end
end

問題を修正する必要があります。

于 2012-12-05T17:53:17.023 に答える