在Ruby中将对象数组转换为JSON

时间:2015-08-02 01:43:50

标签: arrays ruby json

我有一个Person类,其中定义了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\"}"]

虽然在一个to_json上调用Person格式很好:

{"last_name":"Bob","first_name":"Hob","gender":"M","favorite_color":"red","date_of_birth":"01/01/2000"}

1 个答案:

答案 0 :(得分:3)

代码正在转换字符串数组(json字符串),而不是哈希数组。

不要在DELETE FROM `sm_m2epro_listing_product_BACK` WHERE product_id IN (SELECT * FROM (SELECT a.product_id FROM sm_m2epro_listing_product_BACK a WHERE listing_id =8 GROUP BY a.product_id HAVING COUNT( a.product_id ) > 1) qq); 中使用Person#to_json,而是使用Directory#to_json,如下所示:

Person#to_hash