2013-10-21 34 views
0

我從Mongo DB獲取JSON對象。這是JSON。解析jQuery中的javascript變得複雜

**JSON** 
{ 
    "_id" : ObjectId("5265347d144bed4968a9629c"), 
    "name" : "ttt", 
    "features" : { 
     "t" : { 
      "visual_feature" : "t", 
      "type_feature" : "Numeric", 
      "description_feature" : "Time" 
     }, 
     "y" : { 
      "visual_feature" : "y", 
      "type_feature" : "Nominal", 
      "description_feature" : "Values to be mapped to the y-axis" 
     }, 
     "x" : { 
      "visual_feature" : "x", 
      "type_feature" : "Numeric", 
      "description_feature" : "Values to be mapped to the x-axis" 
     } 
    } 
} 

我想從JSON對象中的「功能」屬性建立一個表。 如何在javascript中訪問「features」屬性(它是一個子json對象)?從「visual_feature」,「type_feature」和「description_feature」獲取值很重要。 UPD 我有一個解決方案。

$.ajax({ 
           url: VASERVER_API_LOC + '/visualization/' + visid + '/', 
           type: 'GET', 
           contentType: "application/json", 
           data: tmp_object, 
           success: function(json) { 
            var result = [];       
            var keys = Object.keys(json); 
            keys.forEach(function (key){ 
            result.push(json[key]); 
            }); 

            for(var i=0; i<result.length; i++){ 
            console.log(">>> visual_feature == " + result[i].visual_feature); 
            console.log(">>> type_feature == " + result[i].type_feature); 
            console.log(">>> discription_feature == " + result[i].description_feature); 
            }; 

           } 
          }); 

謝謝!!!

+5

所以...你到目前爲止嘗試過什麼?在這裏拋出一系列需求,等待有人爲你編寫代碼是非常懶惰的。 – Tomalak

+0

for(data.features中的功能)console.log(features [功能] .visual_feature) – mplungjan

+1

他們應該創建一個子域:simplistic-json-questions.stackoverflow.com - 這裏有幾百個這樣的問題 –

回答

2

假設你的JSON結果是一個對象,循環通過像這樣:

for (var feature in result.features) { 
    if (object.hasOwnProperty(feature)) { 
    // do table building stuff 
    console.log(feature); 
    } 
} 

如果它不是一個目標,你會做JSON.parse(result)

要訪問子屬性,你可以做另一個forin循環裏面。

1

JSON創建正常的Javascript對象。

您可以訪問他們的屬性,就像其他任何對象:

var myValue = myObject.features.x.visual_type; 
+0

並非所有的JavaScript環境都自動解析JSON字符串 – Sammaye

+0

@Sammaye:有沒有這樣做? –

+0

@ Qantas94Heavy不,我不這麼認爲,雖然使用圖書館可以使它看起來如此 – Sammaye