2010-12-17 45 views
1

我目前正在使用api提要導入Ruby on Rails項目。作爲Ruby的新手,我不覺得自己在正確使用和管理JSON。有一些功能無法正常工作,我相信它們圍繞着我在處理JSON對象後如何處理。這是我正在與之合作。將JSON消息傳遞給適當的Ruby

{ "auth" : { 
    "person" : { 
     "id" : 1, 
     "name" : "john", 
     "pass" : "123" 
    }, 
    "person" : { 
     "id" : 2, 
     "name" : "fred", 
     "pass" : "789" 
    } 
}} 

,我覺得我可以通過做得到一個簡單的數組:

jsonArray = JSON.parse(persons) 
# the following allows me to target the persons objects 
personArray = jsonArray["auth"]["persons"] 

這裏的問題是試圖做類似personArray.first(5)給我詮釋字符串轉換錯誤。我想把它變成一個可用的散列,我可以做一些操作,但目前看來我只能將它作爲散列迭代。我可能需要對這些結果數據進行排序,從中抽出人員並執行其他操作。我應該如何正確導入?

+1

請注意,上面的Ruby代碼中的'jsonArray'不是['Array'](http://ruby-doc.org/core/類/ Array.html);它是['Hash'](http://ruby-doc.org/core/classes/Hash.html)。將JavaScript對象稱爲「關聯數組」導致了這種粗糙的術語。 – Phrogz 2010-12-17 16:54:39

回答

2

其實直接解析你的json字符串不會給你["auth"]["persons"]。 json字符串裏面沒有"persons"字段......我希望這是一個錯字錯誤。

你爲了所需要的確切格式,使personArray.first(5)工作應該是:

{ 
    "auth": { 
    "persons": [ # Note the square bracket here, which defines an array instead of a hash 
     {"id": 1, "name": "john", "pass": "123"}, 
     {"id": 2, "name": "fred", "pass": "789"} 
    ] 
    } 
} 

,你可以做你想現在要做什麼。

+0

是的,這是一個錯字,謝謝你的提示。我沒有注意到支架/支架問題。這是我無法設計的API,但可能能夠與提供者一起工作。把人看作一個數組而不是獨特的對象會更有意義。我會測試這一點,並會標記這是否有效。謝謝! – 2010-12-17 16:54:21

2

上面的JSON會導致存儲數據少於您想象的JS對象。您將重複覆蓋person密鑰。嘗試複製/粘貼到您的Web瀏覽器的控制檯:

var o = { "auth" : { 
    "person" : { 
    "id" : 1, 
    "name" : "john", 
    "pass" : "123" 
    }, 
    "person" : { 
    "id" : 2, 
    "name" : "fred", 
    "pass" : "789" 
    } 
}}; 

JSON.stringify(o); 
// '{"auth":{"person":{"id":2,"name":"fred","pass":"789"}}}'