【问题标题】:Parse Array hashes in new object with ruby使用 ruby​​ 解析新对象中的数组哈希
【发布时间】:2013-01-02 21:10:32
【问题描述】:

我正在努力处理一些内部带有哈希的数组。我想将它们解析成一个新对象,但不知道该怎么做。

这是数据:

[
  {
    "name"  => "itemHref",
    "value" => "https://192.168.75.145:8281/api/workflows/16da1fa1-7c8b-4602-8d53-17fc5e1fa3ff/"
  },
  {
    "name"  => "id",
    "value" => "16da1fa1-7c8b-4602-8d53-17fc5e1fa3ff"
  },
  {
    "name"  => "categoryName",
    "value" => "FinanzInformatik"
  },
  {
    "name"  => "canExecute",
    "value" => "true"
  },
  {
    "name"  => "categoryHref",
    "value" => "https://192.168.75.145:8281/api/catalog/System/WorkflowCategory/ff8080813b90a145013b90cac51b0006/"
  },
  {
    "name"  => "description",
    "value" => "bekommt alle VMs"
  },
  {
    "name"  => "name",
    "value" => "getAllVms"
  },
  {
    "name"  => "type",
    "value" => "Workflow"
  },
  {
    "name"  => "canEdit",
    "value" => "true"
  }
]

还有,这是我的代码:

require 'rest-client'
require 'json'

class Workflow
  def initialize(itemHref, id, categoryName, canExecute, categoryHref, description, name, type, canEdit)
    @itemHref = itemHref
    @id = id
    @categoryName = categoryName
    @canExecute = canExecute
    @categoryHref = categoryHref
    @description = description
    @name = name
    @type = type
    @canEdit = canEdit
  end
end

json_string = RestClient.get( "http://vcoadmin:vcoadmin@192.168.75.145:8280/api/workflows", :content_type => 'application/json', :accept => 'application/json')
parsed = JSON.parse(json_string)

parsed.each do |a, b|
 if(b.class == Array)
  b.flatten.each do |c|
   p c['attributes']
   #c['attributes'].each
  {
    |f| p f['name'], f['value'] }
  end
 end
end

如何将哈希值放入对象中?我根据值的标识符“名称”来考虑一些事情。

有什么想法吗?

【问题讨论】:

  • 带有散列的数组是parsed.each...等的输出。

标签: ruby arrays json object hash


【解决方案1】:

假设属性的顺序不应该改变:

Workflow.new(*parsed.map {|attr| attr['value']})

【讨论】:

  • 这么简单?该死!但我收到: json_parser.rb:30:in `[]': can't convert String into Integer (TypeError) 我应该在哪一行包含它?解析后的变量在所有每个东西之前都可用。
  • p parsed.map {|attr| attr['value']} 也会产生这个错误。
  • 确保你得到的 json 响应是一个哈希数组。
  • 你是对的。它是一个带有哈希数组的数组 :) 这是对我有用的代码:parsed.each do |a, b| if(b.class== 数组) b.flatten.each 做 |c| Workflow.new(*c['attributes'].map { |attr| attr['value'] }) end end end
【解决方案2】:

我会实现一个可以用哈希初始化的 PORO。因此,您可以将哈希直接传递给创建工作流。

可以看到一个例子:http://pullmonkey.com/2008/01/06/convert-a-ruby-hash-into-a-class-object/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-26
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 2018-09-25
    • 2020-10-29
    • 2021-11-03
    • 2012-07-13
    相关资源
    最近更新 更多