我有一个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,而无需先修复照片阵列?
答案 0 :(得分:3)
显然类型FlickRaw::Response
没有默认的JSON表示。
您有两种选择,可以像往常一样将照片转换为哈希值,也可以使用FlickRaw::Response
方法对to_json
类进行猴子修补,如
class FlickRaw::Response
def to_json
to_hash
end
end
应解决问题。