将类的Ruby数组转换为JSON [英] convert Ruby array of class into JSON
问题描述
我有这样的Ruby数据结构:
I have a Ruby data structure as such:
class Albums
attr_accessor :title, :url
def initialize(title, url)
@title = title
@url = url
end
end
class Albumlist < Albums
attr_accessor :id, :albums
def initialize(id)
@id = id
@albums = Array.new
end
end
然后我制作了一个专辑列表数组,看起来像(使用.inspect方法):
And I made an array of Albumlist which looks like (using .inspect method):
[#<Albumlist:0x8db6390 @id="abc",@albums=[
#<Albums:0x8db6098 @title="123", @url="test">,
#<Albums:0x8db5fe4 @title="456", @url="test">
]>,
#<Albumlist:0x8f4042c @id="def", @albums=[
#<Albums:0x8f49f2c @title="Untitled Album", @url="test">
]>
]
我不确定这个数组是否看起来还可以,但是一旦我在这个数组上使用了.to_json或JSON.generate()方法,我得到的就是:
I am not sure if this array looks okay but once I used the method .to_json or JSON.generate() on this array, all I get is:
["#<Albumlist:0x8db6390>","#<Albumlist:0x8f4042c>"]
看起来Ruby将引用"返回到对象实例. 我想将此数组转换为JSON,
It looks like Ruby returns the "reference" to the object instances. I want to convert this array in JSON which should look like
[
{
"id":"abc"
"albums":[
{
"title":"123",
"url":"test"
},
{
"title":"456",
"url":"test"
}
]
},
{
"id":"def"
"albums":[
{
"title":"Untitled Album",
"url":"test"
}
]
}
]
而且我相信我缺少一些东西,例如将数组转换为某种中间对象?
and I believe I am missing something, such as converting the array into some kind of intermediate object?
替代解决方案
在相册列表类中定义to_json方法,如下所示:
Define a to_json method in class Albumlist as such:
def to_json(*a)
{
"id" => @id,
"albums" => @albums
}.to_json(*a)
end
并改用它..
推荐答案
在这里可以正常工作,可能您不是在正确的时机应用该方法,让我们尝试一下,首先,着眼于像这样的数组:>
Here it works, probably you are not applying the method on the right moment, let's try it, first, focusing on the array with something like this:
require 'rubygems'
require 'active_support/all'
class Albums
attr_accessor :title, :url
def initialize(title, url)
@title = title
@url = url
end
end
class Albumlist < Albums
attr_accessor :id, :albums
def initialize(id)
@id = id
@albums = Array.new
end
end
a = Albums.new("a", "www.a.com")
b = Albums.new("b", "www.b.com")
c = Albums.new("c", "www.c.com")
list_of_albums_list = Array.new
list_a = Albumlist.new(1)
list_b = Albumlist.new(2)
list_a.albums << a
list_a.albums << b
list_b.albums << c
list_of_albums_list << list_a
list_of_albums_list << list_b
puts list_of_albums_list.to_json
输出为:
[{"albums":[{"title":"a","url":"www.a.com"},{"title":"b","url":"www.b.com"}],"id":1},{"albums":[{"title":"c","url":"www.c.com"}],"id":2}]
因此该方法可以按预期工作.
therefore the method works as expected.
这篇关于将类的Ruby数组转换为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!