我正在努力处理一些内部有哈希的数组。我想将它们解析为一个新对象,但不知道如何做到这一点。
以下是数据:
[
{
"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
如何将哈希值放入对象?我想一些基于'name'的东西,它是值的标识符。
有什么想法吗?
答案 0 :(得分:0)
假设不应更改属性的顺序:
Workflow.new(*parsed.map {|attr| attr['value']})
答案 1 :(得分:0)
我会实现一个可以用哈希初始化的PORO。因此,您可以直接将哈希传递给创建工作流。
可以看到一个例子:http://pullmonkey.com/2008/01/06/convert-a-ruby-hash-into-a-class-object/