无法从javascript中的JSON数组中获取值

时间:2016-01-11 09:53:43

标签: javascript json

我无法获取JSON值以检查此人是否在拍照时戴眼镜,该值依赖于四个阵列:照片,标签,属性和眼镜,我想查看值"值"是真还是假。我使用alert()来测试是否获取了值但没有任何结果。我不知道哪个部分出错了

我使用JavaScript来获取JSON值,如下所示:

var facesDet = $.getJSON( APIdetect, function() {
  console.log( "success" );
  console.log(facesDet);
})

.done(function (facesDet, tid) {
    var VALUEIWANT = facesDet.photos[0].tags[0].attributes[0].gender[0].value;

});

JSON值如下所示:

{
"photos" : [
    {
        "url" : "http://tinyurl.com/673cksr",
        "pid" : "F@0c95576847e9cd7123f1e304476b59ae_59ec9bb2ad15f",
        "width" : 375,
        "height" : 409,
        "tags" : [
            {
                "tid" : "TEMP_F@0c95576847e9cd7123f1e304b1dcbe53_59ec9bb2ad15f_56.53_40.83_0_1",
                "recognizable" : true,
                "confirmed" : false,
                "manual" : false,
                "width" : 30.67,
                "height" : 28.12,
                "center" : { "x" : 56.53, "y" : 40.83},
                "eye_left" : { "x" : 66.93, "y" : 33.99},
                "eye_right" : { "x" : 51.73, "y" : 33.99},
                "yaw" : -16,
                "roll" : 0,
                "pitch" : 0,
                "attributes" : {
                    "face" : { "value" : "true", "confidence" : 82 },
                    "gender" : { "value" : "female", "confidence" : 80 },
                    "glasses":{"value" : "true", "confidence" : 100},
                    "dark_glasses":{"value" : "true", "confidence" : 72},
                    "smiling":{"value" : "false", "confidence" : 35}
                }
            }
        ]
    }
],
"status" : "success",
"usage" : {
    "used" : 1,
    "remaining" : 99,
    "limit" : 100,
    "reset_time_text" : "Fri, 21 September 2012 12:57:19 +0000",
    "reset_time" : 1348232239
}
}

4 个答案:

答案 0 :(得分:2)

您的访问权限错误。你有一个对象,但你把它当成一个数组

var VALUEIWANT = facesDet.photos[0].tags[0].attributes[0].gender[0].value;
//                                                    ^^^  and  ^^^

正确访问:

var VALUEIWANT = facesDet.photos[0].tags[0].attributes.gender.value;

数据:

"attributes" : {
    "face" : { "value" : "true", "confidence" : 82 },
    "gender" : { "value" : "female", "confidence" : 80 },
    "glasses":{"value" : "true", "confidence" : 100},
    "dark_glasses":{"value" : "true", "confidence" : 72},
    "smiling":{"value" : "false", "confidence" : 35}
}

答案 1 :(得分:2)

您尝试从数组中获取性别值:

var VALUEIWANT = facesDet.photos[0].tags[0].attributes[0].gender[0].value;

但是在你的json中它的对象,所以你应该使用:

var VALUEIWANT = facesDet.photos[0].tags[0].attributes.gender.value;

答案 2 :(得分:2)

尝试这个。

facesDet.photos[0].tags[0].attributes.gender.value

答案 3 :(得分:0)

getJSON返回一个promise而不是响应,你需要使用这段代码:

$.getJSON( APIdetect, function(facesDet) {
  console.log( "success" );
  console.log(facesDet);
})