Ruby Hash converted to JSON only shows object name

2019-07-25 11:00发布

问题:

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?

回答1:

Apparently the type FlickRaw::Response has no default JSON representation.

You have two options, either transform the photos to hashes as you did, or monkey-patch the FlickRaw::Response class with a to_json method as in

class FlickRaw::Response
  def to_json
    to_hash
  end
end

which should fix the issue.