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

Aas*_*ish 1 ruby arrays json ruby-on-rails

我试过搜索,但找不到任何适当的解决方案.我试图使用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"
    }
  }
]
Run Code Online (Sandbox Code Playgroud)

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

require 'rest-client'

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

puts output[0]["username"]
Run Code Online (Sandbox Code Playgroud)

我的用户名没有输出.

spi*_*ann 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"]
Run Code Online (Sandbox Code Playgroud)

  • 关注点分离:Web中使用了许多不同的数据格式:JSON,HTML,CSV,XML,TXT - 仅举几例.恕我直言,它们没有多大意义,包括将每个解析器转换为像"RestClient"这样的工具. (2认同)