2017-07-03 91 views
1

我试过搜索,但找不到任何适当的解决方案。我试图用没有根密钥的Ruby中的RestClient gem来解析JSON。当我解析它时,它会返回空白值。如何解析JSON没有根密钥

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

[ 
    { 
    "id": 1, 
    "name": "Leanne Graham", 
    "username": "Bret", 
    "email": "[email protected]", 
    "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": "[email protected]", 
    "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"] 

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

+0

这不能解决你的问题,但尝试使用'p'而不是'puts'作为调试输出。 'p'显示了正在打印的“检查”格式,这可能更有用。 –

+0

谢谢@WayneConrad我会用这个。 – Aashish

回答

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

非常感谢@spickemann解决了我的问题。干杯! – Aashish

+2

问题分离:Web中使用了许多不同的数据格式:JSON,HTML,CSV,XML,TXT - 只是名称相同而已。恕我直言,它没有太大的意义,包括解析器为每个他们到'RestClient'工具。 – spickermann