【问题标题】:How to parse JSON without root key如何在没有根键的情况下解析 JSON
【发布时间】:2017-07-03 17:11:33
【问题描述】:

我尝试搜索,但找不到任何合适的解决方案。我正在尝试在没有根密钥的情况下使用 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"]

我没有得到用户名的输出。

【问题讨论】:

  • 这并不能解决您的问题,但请尝试使用p 而不是puts 进行调试输出。 p 显示正在打印的内容的“检查”格式,这可能更有用。
  • 谢谢@WayneConrad 我会用这个。

标签: ruby-on-rails arrays json ruby


【解决方案1】:

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"]

【讨论】:

  • 关注点分离:Web 中使用了许多不同的数据格式:JSON、HTML、CSV、XML、TXT - 只是名称相同。恕我直言,将每个解析器包含在RestClient之类的工具中没有多大意义。
猜你喜欢
  • 2012-03-23
  • 2019-11-16
  • 1970-01-01
  • 2018-06-02
  • 1970-01-01
  • 2016-08-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多