ruby - 如何解析这个LinkedIn的哈希?

时间:2012-03-22 20:29:30

标签: ruby-on-rails ruby parsing hash linkedin

从LinkedIn API我得到了这个哈希:

> #<LinkedIn::Mash all=[#<LinkedIn::Mash api_standard_profile_request=#<LinkedIn::Mash headers=#<LinkedIn::Mash
> all=[#<LinkedIn::Mash name="x-li-auth-token" value="name:_nNI">]
> total=1> url="http://api.linkedin.com/v1/people/asdasfga">
> first_name="first name" headline="job position"
> id="id of user" industry="industry"
> last_name="last name" location=#<LinkedIn::Mash
> country=#<LinkedIn::Mash code="en"> name="country">
> site_standard_profile_request=#<LinkedIn::Mash
> url="http://www.linkedin.com/profile?viewProfile=&key=key_number&authToken=_nNI&authType=name&trk=api*a_12346*s_12346*">>]
> total=1>

我已经很长时间尝试获取first_nameurlcountry,但我仍然无法解析它。 有谁可以帮助我?

提前致谢

编辑尝试:

linkedin.connections.each do |item|
   puts item
end

给出

total
1
all
#<LinkedIn::Mash api_standard_profile_request=#<LinkedIn::Mash headers=#<LinkedIn::Mash all=[#<LinkedIn::Mash name=...

当我尝试

linkedin.connections.api_standard_profile_request.each do |item|
   puts item
end
然后我得到了

undefined method `each' for nil:NilClass

2 个答案:

答案 0 :(得分:1)

试试这个:

linkedin.all.each do |profile|
  puts profile.first_name
end

答案 1 :(得分:1)

我建议您使用p而不是puts来调试对象。它会在您正在打印的对象上调用inspect而不是to_s,这会为您提供有关该对象的更多信息。

接下来,查看Hashie::Mash上的文档。你的LinkedIn::Mash对象继承自这个类,但LinkedIn没有提供太多的文档,所以你必须继续上传继承链。

由于Hashie::Mash是类似哈希的对象,因此在迭代它时应使用each_pair来获取哈希中的每个键值对,而不是一次获取一个键或值:

linkedin.connections.each_pair do |key, value|
  p key
  p value
end

这些都没有真正回答您的问题,但希望您可以从调试工作中获得更多信息。我猜你需要做这样的事情:

linkedin.connections[0].url

但我并不积极。