我正在使用batchbook ruby gem构建一个简单的列表页面,从我的batchbook crm中提取各种字段。如果我提取某家公司的所有属性,我最终会得到这样的结果:
{"id"=>13, "name"=>"John Deer", "notes"=>nil, "small_image"=>nil, "large_image"=>nil, "tags"=>[#<BatchBook::Tag:0x00000001df6438 @attributes={"id"=>"1002", "name"=>"portfolio", "supertag"=>"true", "fields"=>#<BatchBook::Tag::Fields:0x00000001dee5a8 @attributes={"logo"=>"img/fr-logo-button-sm.png", "description"=>"We make tractors."}, @prefix_options={}>}, @prefix_options={}>], "locations"=>[#<BatchBook::Location:0x00000001dea048 @attributes={"id"=>14, "label"=>"main", "primary"=>true, "email"=>"***@johndeer.com", "website"=>"http://johndeer.com", "phone"=>nil, "cell"=>nil, "fax"=>nil, "street_1"=>nil, "street_2"=>nil, "city"=>nil, "state"=>nil, "postal_code"=>nil, "country"=>nil}, @prefix_options={}>], "mega_comments"=>[], "created_at"=>"Thu Jun 02 22:32:16 UTC 2011", "updated_at"=>"Thu Jun 02 22:40:03 UTC 2011"}
我如何解析它,从我的"公文包"SuperTag中只提取"徽标"或"描述"?
也许只使用@company.supertag
对象更简单,它给了我这个:
[{"id"=>15, "name"=>"portfolio", "fields"=>{"logo"=>"img/fr-logo-button-sm.png", "description"=>"We make tractors."}}]
但是,我该如何提取单独的字段"徽标"或"描述"?
我觉得这应该是一个简单的过程,也许我在语法上很吃力,或者让它变得比需要的更复杂,但你能帮我吗?
我不确定你的第一个类似哈希的字符串是关于什么的,所以我们来看看@company.supertag
的输出值:
[
{
"id" => 15,
"name" => "portfolio",
"fields" => {
"logo" => "img/fr-logo-button-sm.png",
"description" => "We make tractors."
}
}
]
我冒昧地把它重新格式化成可读的东西。外部的方括号表示它是一个数组,大括号位于下一级,因此数组包含哈希。Array和Hash都使用[]
来访问它们的元素,因此,如果整个数据结构都在a
中,并且我们记得Array从0开始索引,那么我们从以下内容开始:
a[0]['fields']
这给了我们一个内部散列:
"fields" => {
"logo" => "img/fr-logo-button-sm.png",
"description" => "We make tractors."
}
更进一步:
logo = a[0]['fields']['logo']
desc = a[0]['fields']['description']