Himanshu Yadav
Himanshu Yadav

Reputation: 13585

Accessing JSON key values without loop

Receiving JSON response like this

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"];

It works fine in for loop like this:

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

But I am not able to access it outside for loop. Tried:

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

and

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

and

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

But nothing worked for me.

Upvotes: 0

Views: 67

Answers (1)

Quentin
Quentin

Reputation: 943625

Your JSON isn't JSON. It is a set of JavaScript object literals, and when it hits [object Object], it errors because you can't have someIdentifier someOtherIdentifier in an array literal.

Values in arrays have to be separated by commas, but it looks like you intended to have object literals there with some specific values. When you create the JavaScript, you need to express those as proper object literals instead of simply casting the objects to strings.

Upvotes: 3

Related Questions