2017-07-03 83 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