开发者

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 开发者_StackOverflow中文版the following output:

cell
work (123) 456 7890


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


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.


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?


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜