【问题标题】:Converting an array of objects to JSON in Ruby在 Ruby 中将对象数组转换为 JSON
【发布时间】:2015-08-02 01:43:50
【问题描述】:

我有一个 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\"}"]

而在Person 上调用to_json 的格式很好:

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

【问题讨论】:

    标签: arrays ruby json


    【解决方案1】:

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

    不要在Directory#to_json 中使用Person#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
    

    【讨论】:

      猜你喜欢
      • 2017-01-18
      • 2011-07-07
      • 2012-07-21
      • 2020-10-02
      • 1970-01-01
      • 1970-01-01
      • 2018-09-12
      相关资源
      最近更新 更多