Rails - 我无法正确解析JSON响应

时间:2015-11-10 15:55:35

标签: ruby json github-api

我无法正确解析JSON响应。只是显示空白页面。我的代码如下所示。

h = response.to_json
@data = h["items"][0]["login"]

JSON回复

[
    ["total_count", 2782],
    ["incomplete_results", false],
    ["items", [{
      "login": "datomnurdin",
      "id": 5416242,
      "avatar_url": "https://avatars.githubusercontent.com/u/5416242?v=3",
      "gravatar_id": "",
      "url": "https://api.github.com/users/datomnurdin",
      "html_url": "https://github.com/datomnurdin",
      "followers_url": "https://api.github.com/users/datomnurdin/followers",
      "following_url": "https://api.github.com/users/datomnurdin/following{/other_user}",
      "gists_url": "https://api.github.com/users/datomnurdin/gists{/gist_id}",
      "starred_url": "https://api.github.com/users/datomnurdin/starred{/owner}{/repo}",
      "subscriptions_url": "https://api.github.com/users/datomnurdin/subscriptions",
      "organizations_url": "https://api.github.com/users/datomnurdin/orgs",
      "repos_url": "https://api.github.com/users/datomnurdin/repos",
      "events_url": "https://api.github.com/users/datomnurdin/events{/privacy}",
      "received_events_url": "https://api.github.com/users/datomnurdin/received_events",
      "type": "User",
      "site_admin": false,
      "score": 1.0
    },..

我想要的是这样的

datomnurdin

P.S:Github API使用此库https://github.com/peter-murach/github

的原始响应
> #<Hashie::Mash avatar_url="https://avatars.githubusercontent.com/u/5416242?v=3"
> events_url="https://api.github.com/users/datomnurdin/events{/privacy}"
> followers_url="https://api.github.com/users/datomnurdin/followers"
> following_url="https://api.github.com/users/datomnurdin/following{/other_user}" gists_url="https://api.github.com/users/datomnurdin/gists{/gist_id}"
> gravatar_id="" html_url="https://github.com/datomnurdin" id=5416242
> login="datomnurdin"
> organizations_url="https://api.github.com/users/datomnurdin/orgs"
> received_events_url="https://api.github.com/users/datomnurdin/received_events" repos_url="https://api.github.com/users/datomnurdin/repos" score=1.0
> site_admin=false
> starred_url="https://api.github.com/users/datomnurdin/starred{/owner}{/repo}" subscriptions_url="https://api.github.com/users/datomnurdin/subscriptions"
> type="User" url="https://api.github.com/users/datomnurdin">,..

1 个答案:

答案 0 :(得分:2)

您链接的Github库返回Hashie::Mash实例。

不应该尝试将返回的结果转换为json(显然是一个字符串),只需使用:

h = result_as_returned_by_github_library
@data = h["items"][0]["login"]