[英]Converting an array of objects to JSON in Ruby
我有一个Person
类, to_json
定义了to_json
方法:
class Person
...
def to_json
{
last_name: @last_name,
first_name: @first_name,
gender: @gender,
favorite_color: @favorite_color,
date_of_birth: @date_of_birth
}.to_json
end
end
在另一个类中,我正在处理一系列Person
对象。 如何将此数组作为一长串有效的JSON数据返回? 我试过像这样在新类中定义to_json
:
class Directory
...
def to_json
@people.map do |person|
person.to_json
end.to_json
end
end
但这给了我一些奇怪的外观,在整个JSON数据中散布了许多"
和\\
字符,如下所示:
["{\\"last_name\\":\\"Dole\\",\\"first_name\\":\\"Bob\\",\\"gender\\":\\"M\\",\\"favorite_color\\":\\"Red\\",\\"date_of_birth\\":\\"01/02/1950\\"}","{\\"last_name\\":\\"Man\\",\\"first_name\\":\\"Bean\\",\\"gender\\":\\"M\\",\\"favorite_color\\":\\"Blue\\",\\"date_of_birth\\":\\"04/03/1951\\"}","{\\"last_name\\":\\"Man\\",\\"first_name\\":\\"Green\\",\\"gender\\":\\"F\\",\\"favorite_color\\":\\"Yellow\\",\\"date_of_birth\\":\\"02/15/1955\\"}","{\\"last_name\\":\\"Clinton\\",\\"first_name\\":\\"Bill\\",\\"gender\\":\\"M\\",\\"favorite_color\\":\\"Orange\\",\\"date_of_birth\\":\\"02/23/1960\\"}"]
而对一个Person
调用to_json
格式很不错:
{"last_name":"Bob","first_name":"Hob","gender":"M","favorite_color":"red","date_of_birth":"01/01/2000"}
该代码正在转换字符串数组(json字符串),而不是哈希数组。
而不是使用的Person#to_json
在Directory#to_json
,使用Person#to_hash
类似以下内容:
class Person
def to_hash
{
last_name: @last_name,
first_name: @first_name,
gender: @gender,
favorite_color: @favorite_color,
date_of_birth: @date_of_birth
}
end
def to_json
to_hash.to_json
end
end
class Directory
def to_json
@people.map do |person|
person.to_hash
end.to_json
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.