如何在没有根密钥的情况下解析JSON

时间:2017-07-03 17:11:33

标签: ruby-on-rails arrays json ruby

我试过搜索但找不到合适的解决办法。我试图使用Ruby中的RestClient gem解析JSON而不使用根密钥。当我解析它时,它返回空值。

这是我试图解析的示例JSON。

[
  {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "Sincere@april.biz",
    "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
    },
    "phone": "1-770-736-8031 x56442",
    "website": "hildegard.org",
    "company": {
      "name": "Romaguera-Crona",
      "catchPhrase": "Multi-layered client-server neural-net",
      "bs": "harness real-time e-markets"
    }
  },
  {
    "id": 2,
    "name": "Ervin Howell",
    "username": "Antonette",
    "email": "Shanna@melissa.tv",
    "address": {
      "street": "Victor Plains",
      "suite": "Suite 879",
      "city": "Wisokyburgh",
      "zipcode": "90566-7771",
      "geo": {
        "lat": "-43.9509",
        "lng": "-34.4618"
      }
    },
    "phone": "010-692-6593 x09125",
    "website": "anastasia.net",
    "company": {
      "name": "Deckow-Crist",
      "catchPhrase": "Proactive didactic contingency",
      "bs": "synergize scalable supply-chains"
    }
  }
]

我得到了正确的输出,但是当我尝试访问特定字段时,我得到空白输出:

require 'rest-client'

output = RestClient.get 'https://jsonplaceholder.typicode.com/users'
puts output

puts output[0]["username"]

我没有输入用户名。

1 个答案:

答案 0 :(得分:9)

rest-client不解析JSON本身。您需要将此作为明确的步骤:

require 'rest-client'

response = RestClient.get('https://jsonplaceholder.typicode.com/users')
output = JSON.parse(response.body) # or just JSON.parse(response) would also work

puts output[0]["username"]