2013-10-06 70 views
0

我有以下json對象,我想閱讀它(從中訪問一些數據)在純Javascript中閱讀複雜的JSON

我該怎麼用Javascript來做到這一點?

var allSites = 
    {"oldSites": 
     [ 
      { 
       "site0" : "http://site0.com/", 
       "site1" : "http://site1.com/", 
       "site2" : "http://site2.com/" 
      } 
     ], 
    "newSites": 
     [ 
      { 
       "site0" : "http://site0/new", 
       "site1" : "http://site1/new", 
       "site2" : "http://site2/new" 
      } 
     ] 
    }; 

這就是我所做的,但我得到了未定義。

var allSites = eval(allSites); 
alert(allSites.oldSites.site0); 

謝謝。

+1

它不是一個JSON對象,因爲JSON只是一個格式約定來表示** JAVASCRIPT LITERAL OBJECTS **以** STRING **的形式提供。如果沒有對對象進行評估(無論如何用JSON字符串,你應該使用'JSON.parse') –

+1

試試這個:alert(allSites.oldSites [0] .site0); –

回答

3

如果你的對象是像你所描述的那樣定義的,那不是JSON,你不需要使用eval

然後,由於oldSites是一個數組,因此您必須對其進行索引,如oldSites[0]以獲取第一個值。

然後,獲取檢索對象的site0鍵。

所以,你應該使用:allSites.oldSites[0].site0

+0

謝謝,工作你是完全正確的:) – OussamaLord

+0

如果你沒有問題,請標記解決方案之一[如接受](http://stackoverflow.com/help/someone-answers)。 –

2

使用

allSites.oldSites[0].site0 

allSites.oldSites是一個數組。所以你必須迭代使用索引

1

請刪除的方括號,這使得oldSites數組

var allSites = 
    {"oldSites": 

      { 
       "site0" : "http://site0.com/", 
       "site1" : "http://site1.com/", 
       "site2" : "http://site2.com/" 
      } 
     , 
    "newSites": 

      { 
       "site0" : "http://site0/new", 
       "site1" : "http://site1/new", 
       "site2" : "http://site2/new" 
      } 

    }; 
+0

我使用這種解決方案工作良好,但我需要一些原因(編碼原因)訪問site0索引像這樣:'allSites.oldSites [0]'而不是'allSites.oldSites.site0'有可能嗎? – OussamaLord

+0

好吧我把它變成簡單的愛心感謝 – OussamaLord

+0

你的eval聲明有'allSites.oldSites.site0',所以刪除'['']'是選項,但是這取決於需求:) – Ani