2010-07-18 97 views
2

我是json的新手。我有JSON輸出,看起來像這樣如何從json輸出中檢索值?

[ 
    { 
     "employees": { 
      "education": "BE\/B.Tech" 
     }, 
     "0": { 
      "count": "1" 
     } 
    }, 
    { 
     "employees": { 
      "education": "MBA" 
     }, 
     "0": { 
      "count": "3" 
     } 
    } 
] 

我想檢索員工的教育和計數。我已經嘗試過,但我無法檢索值。

我很感激任何幫助。

謝謝。

+0

您可以粘貼您嘗試使用的代碼來檢索此JSON輸出嗎? – BoltClock 2010-07-18 19:07:27

回答

10

假設你的JSON字符串在可變$json,它是這樣的:

var employees_list = JSON.parse($json); 

然後,您可以通過訪問信息:

employees_list[0].employees.education // gives you "BE\/B.Tech" 
// and 
employees_list[0]["0"].count // gives you 1. 

您還可以循環數組和訪問過所有不同的education這種方式。

更新:

爲了更好地展現其表達訪問哪些信息:

[          // employees_list 
    {         // employees_list[0] 
     "employees": {     // employees_list[0].employees 
      "education": "BE\/B.Tech" // employees_list[0].employees.education 
     }, 
     "0": {       // employees_list[0]["0"] 
      "count": "1"    // employees_list[0]["0"].count 
     } 
    }, 
    {         // employees_list[1] 
     "employees": {     // employees_list[1].employees 
      "education": "MBA"   // employees_list[1].employees.education 
     }, 
     "0": {       // employees_list[1]["0"] 
      "count": "3"    // employees_list[1]["0"].count 
     } 
    } 
] 

一般employees_list[0].employees相同employees_list[0]["employees"]但這並不對數字工作,因爲屬性和變量是不允許以數字開頭。所以你可以只使用使用employees_list[0].["0"]而不是employees_list[0].0


雖然你的JSON字符串的結構看起來有點奇怪。如果可以的話,你應該考慮採用不同的結構。

例如:

[ 
    { 
     "education": "BE\/B.Tech", 
     "count": "1" 
    }, 
    { 
     "education": "MBA" 
     "count": "3" 
    } 
] 

在原來的JSON字符串的"0"關鍵似乎起不到任何作用,只是在接入複雜。

+0

我知道輸出看起來很奇怪。 var employees_list; $ .getJSON('url',function(data){ employees_list = JSON.parse(data); showAlert(); }); (){ function showAlert } 我試過但不起作用。 – Nick 2010-07-18 19:31:30

+0

@Nick:如果你使用'getJSON',那麼你不需要解析它。它已經被解析。 'data [0] .employees.education'應該可以工作。 – 2010-07-18 19:41:59