tnt-rox
tnt-rox

Reputation: 5548

Access json value using JavaScript object notation

I am unable to access a json value

{"phone": [
{
    "@attributes": {
        "type": "cell",
        "ext": ""
    }
}, "(123) 456 7890", {
    "@attributes": {
        "type": "work",
        "ext": ""
    }
}
]}

using the following JavaScript: psudo

for each phone line ...

console.log(["@attributes"].type);
console.log(this); 
console.log(["@attributes"].ext);

... end for

I expected the following output:

cell
work (123) 456 7890

Upvotes: 0

Views: 16494

Answers (4)

xkeshav
xkeshav

Reputation: 54022

actually your json structure is not perfect, so here is the solution for your desired output

var json = {"phone": [
{
    "@attributes": {
        "type": "cell",
        "ext": ""
    }
}, "(123) 456 7890", {
    "@attributes": {
        "type": "work",
        "ext": ""
    }
}
]};
 console.log(json['phone'][0]['@attributes'].type);
 console.log('<br/>'+json['phone'][1]);
 console.log('<br/>'+json['phone'][2]['@attributes'].type);

DEMO

Upvotes: 4

muffir
muffir

Reputation: 447

I think your phone array is quite messy because you have:

phone[0] === {'@attributes':...}
phone[1] === '(123) 456 7890'
phone[2] === {'@attributes':...}

Is that what you realy wanted to have there?

Upvotes: 0

Adeel
Adeel

Reputation: 19228

since phone is an array, try this,

   for(var i=0;i<phone.length;i++)
     console.log(phone[i].["@attributes"].type);

Also surround your response with {, as it is currently an invalid json.

Upvotes: 2

Dave Mackintosh
Dave Mackintosh

Reputation: 2796

I'm pretty sure you can't start any object, associative array key or well anything with a non-alphanumerical character.

Also you have 3 calls to console and only two lines of expected output? What does console.log(this) output?

Upvotes: 0

Related Questions