我有一个RubyFlickRaw
响应,希望将其转换为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一样?
最佳答案
显然,FlickRaw::Response
类型没有默认的JSON表示。
您有两个选项,要么像您所做的那样将照片转换为散列,要么像中那样用FlickRaw::Response
方法修补to_json
类
class FlickRaw::Response
def to_json
to_hash
end
end
这应该能解决问题。