我收到错误" 未定义方法`[]'为零:NilClass "当试图从json解析的哈希显示一个字段。如何显示coll_title数据?
来自 alinks 的数据:
[{
"role"=>"source",
"relator"=>"dnr",
"terms"=>[],
"_resolved"=>{
"lock_version"=>0,
"publish"=>true,
"display_name"=>{
"coll_num"=>"024",
"coll_title"=>"Collection Title"
}
}
}]
代码:
def display_agents(hash, opts = {})
html = "<div><small>"
html << "<ul style='list-style-type:none'>"
alinks = JSON.parse( hash["json"] )["linked_agents"]
alinks.each do |_resolved|
html << "<li>#{_resolved["display_name"]["coll_title"]}</li>"
end
html << "</ul>"
html << "</small></div><div class='clearfix'></div>"
html.html_safe
end
电话:
<td>
<% if result['primary_type'] === "resource" or result['primary_type'] === "digital_object" or result['primary_type'] === "accession" %>
<%= display_agents(result) %>
<% end %>
</td>
错误:
undefined method `[]' for nil:NilClass
Extracted source (around line #85):
82: <% end %>
83: <td>
84: <% if result['primary_type'] === "resource" or result['primary_type'] === "digital_object" or result['primary_type'] === "accession" %>
85: <%= display_agents(result) %>
86: <% end %>
87: </td>
88: <%#<td>%>
编辑:添加了方法调用和错误显示。
答案 0 :(得分:2)
假设你显示的alinks数据是linked_agents数组(你的问题不是100%清楚) - 那么你需要
alinks.each do |agent_link|
html << "<li>#{agent_link["_resolved"]["display_name"]["coll_title"]}</li>"
end
答案 1 :(得分:1)
_resolved
块中的each
是整个哈希,即。使用您的示例数据,它等于:
{
"role"=>"source",
"relator"=>"dnr",
"terms"=>[],
"_resolved"=>{
"lock_version"=>0,
"publish"=>true,
"display_name"=>{
"coll_num"=>"024",
"coll_title"=>"Collection Title"
}
}
}
您能看到为什么检索 哈希返回"display_name"
的{{1}}键的原因吗?