簡體   English   中英

不知道鍵值時,如何從JSON響應中檢索鍵?

[英]How do I retrieve a key from a JSON response, when I don't know the key value?

這可能真的很簡單,但是我已經把頭撞在牆上試圖弄清楚。

我需要從JSON響應中獲取一個值,但是響應中返回的鍵是隨機的,因此我無法直接引用它來進行深入研究。

這是我得到的回復:

var c = {
         "success": { 
                    "7d40ab5352b0471cae5bdefc2e032840": { 
                          "__type__" : "user",
                          "__id__" : "7d40ab5352b0471cae5bdefc2e032840"
                    }

         },
         "errors": {}
         }

我需要的是您在此處看到的隨機字符串-ID。 我已經嘗試過各種方法,但終生無法弄清楚如何以字符串形式返回ID。 我試圖用數組符號c.success[0][0]來解決這個問題,但沒有用。 顯然,我不能使用點符號,因為我不知道在.success之后加上什么。

有人知道在事先不知道數組鍵的情況下該怎么做嗎? 我想確保以一種最佳做法而不是黑客的方式來執行此操作。

謝謝...如果我因某種原因錯過了本已發布的答案,請以這種方式發送給我。 我搜索了幾天,找不到此答案。

for (var prop in c.success) {
  alert(c.success[prop].__id__); // Replace the alert with whatever you want to do with the ID
  // break; // Uncomment if there can be more than one ID returned and you only want one
}

如果鍵與__id__值相同,則只需執行以下操作:

for (var prop in c.success) {
  alert(prop); // Replace the alert with whatever you want to do with the ID
  // break; // Uncomment if there can be more than one ID returned and you only want one
}

盡管ŠimeVidas對Object.keys的使用更為優雅,但除非使用所謂的他,否則您仍需要上述代碼才能在較舊的瀏覽器中工作(即,添加一些額外的代碼以使您今天使用新的標准,即,一個Object.keys的實現,它的實現與上述操作相同,除非已經存在內置版本,在這種情況下,填充程序將優先使用內置版本)。

這個:

var obj = c.success[ Object.keys( c.success )[0] ];

obj.__type__ // "user"
obj.__id__ // "7d40ab5352b0471cae5bdefc2e032840"

現場演示: http //jsfiddle.net/AJaBS/

您可以使用一個簡單的循環:

for (var id in c.success) {
    var obj = c.success[id];
    // do something
}

如果要確保僅處理對象中的第一個屬性,則可以添加一個break; 聲明到底。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM