我有一个这样结构的ruby散列:
jotform = {
'1' => {
'name' => 'theGreat',
'order' => '1',
'text' => 'xxxxx',
'type' => 'control_head'
},
'3' => {
'name' => 'clickTo',
'order' => '2',
'text' => '<p>Final date to apply is August 29</p>',
'type' => 'control_text'
},
'4' => {
'name' => 'personalDetails',
'order' => '3',
'text' => 'Personal Details',
'type' => 'control_head'
},
'5' => {
'name' => 'name',
'order' => '4',
'sublabels' =>
'{"prefix":"Prefix","first":"First Name","middle":"Middle Name","last":"Last Name","suffix":"Suffix"}',
'text' => 'Name',
'type' => 'control_fullname',
'answer' => {
'first' => 'Example',
'last' => 'Example'
},
'prettyFormat' => 'Example'
},
'9' => {
'name' => 'country',
'order' => '5',
'text' => 'Country',
'type' => 'control_dropdown',
'answer' => 'Germany'
},
'10' => {
'name' => 'email',
'order' => '6',
'text' => 'Email',
'type' => 'control_email',
'answer' => 'picco@example.com'
},
'15' => {
'name' => 'pageBreak',
'order' => '8',
'text' => 'Page Break',
'type' => 'control_pagebreak'
},
'16' => {
'name' => 'contributions',
'order' => '9',
'text' => 'Contributions',
'type' => 'control_head'
}
}
这是我从jotform收到的有效载荷,我必须在我的应用程序中处理。问题是我不知道字段的顺序:这个哈希有一些键('1'
,'2'
,…),相当于形式的答案。
我必须得到漂亮格式的名字和电子邮件,所以我试着得到这些值。
这里的电子邮件键是'10'
,名称键是'5'
,但它们可以在下一个表单中更改。
我试试
jotform.select { |_key, hash| hash['name'] == 'email' }
但是它返回
{
'10' => {
'name' => 'email',
'order' => '6',
'text' => 'Email',
'type' => 'control_email',
'answer' => 'example@example.com'
}
}
我需要得到键('10'
),如果有一个匹配到这个键的值,但我无法理解如何。
从select
调用的结果:
h = jotform.select{ |key, hash| hash["name"] == "email" }
你可以通过:
h.keys.first
#=> "10"
和via值:
h.values.first["answer"]
#=> "example@example.com"
需要first
,因为(理论上)可能有多个电子邮件条目。
这个格式真奇怪。
我不确定我理解它,但假设name
是唯一的,你可以重新索引你的哈希并使用name
作为键:
new_data = jotform.map do |id, h|
key = h.delete 'name'
[key, h.merge('id' => id)]
end.to_h
新格式如下:
{"theGreat"=>
{"order"=>"1", "text"=>"xxxxx", "type"=>"control_head", "id"=>"1"},
"clickTo"=>
{"order"=>"2",
"text"=>"<p>Final date to apply is August 29</p>",
"type"=>"control_text",
"id"=>"3"},
"personalDetails"=>
{"order"=>"3",
"text"=>"Personal Details",
"type"=>"control_head",
"id"=>"4"},
"name"=>
{"order"=>"4",
"sublabels"=>
"{"prefix":"Prefix","first":"First Name","middle":"Middle Name","last":"Last Name","suffix":"Suffix"}",
"text"=>"Name",
"type"=>"control_fullname",
"answer"=>{"first"=>"Example", "last"=>"Example"},
"prettyFormat"=>"Example",
"id"=>"5"},
"country"=>
{"order"=>"5",
"text"=>"Country",
"type"=>"control_dropdown",
"answer"=>"Germany",
"id"=>"9"},
"email"=>
{"order"=>"6",
"text"=>"Email",
"type"=>"control_email",
"answer"=>"picco@example.com",
"id"=>"10"},
"pageBreak"=>
{"order"=>"8",
"text"=>"Page Break",
"type"=>"control_pagebreak",
"id"=>"15"},
"contributions"=>
{"order"=>"9", "text"=>"Contributions", "type"=>"control_head", "id"=>"16"}}
没有信息丢失,应该更容易访问。要获得电子邮件地址,您可以简单地使用:
new_data["email"]["answer"]
#=> "picco@example.com"