无循环访问JSON键值

时间:2014-03-10 21:39:24

标签: javascript json

像这样接收JSON响应

responses = {
            "http://www.example.com/firts": {
                error: [object Object],
                response: [object Object],
                body: [object Object]
            },
            "http://www.example.com/second": {
                error: [object Object],
                response: [object Object],
                body: [object Object]
            },
            "http://www.example.com/third": {
                error: [object Object],
                response: [object Object],
                body: [object Object]
            }
        }

var urls = ["http://www.example.com/firts", "http://www.example.com/second", "http://www.example.com/third"];

它在for循环中运行良好:

for(url in responses) {
        var response = responses[url];
        console.log('Got the response '+response.response.statusCode);
}

但是我无法在外面循环访问它。 尝试:

var response = responses[urls[0]];
console.log('Got the response '+response.response.statusCode);

var response = responses["http://www.example.com/firts"];
console.log('Got the response '+response.response.statusCode);

var response = responses[0][urls[0]];
    console.log('Got the response '+response.response.statusCode);

但没有任何对我有用。

1 个答案:

答案 0 :(得分:3)

您的JSON不是JSON。它是一组JavaScript对象文字,当它到达[object Object]时,它会出错,因为你不能在数组文字中有someIdentifier someOtherIdentifier

数组中的值必须用逗号分隔,但看起来你打算在那里有一些特定值的对象文字。在创建JavaScript时,您需要将它们表达为正确的对象文字,而不是简单地将对象转换为字符串。