0

我正在使用 Faraday 从 Web 服务中检索 JSON 编码的对象,但是 Web 服务使用可怕的键字符串作为键:值对,例如我想要 'description' 的 'Memo' 和我想要 'manager' 的 'projectManager' .

如何在法拉第检索密钥并将结果插入 Ruby 哈希时对其进行转换?

我希望这是一个已解决的问题,但确实很难找到。(我看到很多帖子询问有关在 JSON.parse() 中将符号转换为字符串的问题)。

4

1 回答 1

1

考虑将数据映射到 Virtus 对象

https://github.com/solnic/virtus

class Foo
  include Virtus.model

  attribute :manager, String
  attribute :description, String

  def self.map(json)
    # you only need to map the ones that differ
    new(json.merge!({
      manager: json["projectManager"],
      description: json["Memo"]
    })
  end
end

然后根据需要循环遍历您的数据(或者如果有意义,可以创建一个顶级 virtus 对象)

payload = ... # json retrieved by Faraday as array of ruby hashes
foo_list = payload.map do |item|
  Foo.map(item)
end
于 2014-05-21T01:08:50.210 回答