在javascript中解析复杂的json

时间:2013-10-21 14:40:47

标签: javascript json mongodb

我从Mongo DB获取JSON对象。这是JSON。

**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对象中的“features”属性构建表。 如何在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);
                                    };

                                }
                            });

谢谢!!!

2 个答案:

答案 0 :(得分:2)

假设您的JSON结果是一个对象,请像这样循环:

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

如果它不是对象,您将执行JSON.parse(result)

要访问子属性,您可以在其中执行另一个for in循环。

答案 1 :(得分:1)

JSON创建普通的Javascript对象。

您可以像访问任何其他对象一样访问其属性:

var myValue = myObject.features.x.visual_type;