最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Access json value using JavaScript object notation - Stack Overflow

programmeradmin1浏览0评论

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

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
Share Improve this question edited Aug 26, 2011 at 10:05 tnt-rox asked Aug 26, 2011 at 9:06 tnt-roxtnt-rox 5,5682 gold badges39 silver badges52 bronze badges 1
  • @diEcho.. sorry about the {} cut! – tnt-rox Commented Aug 26, 2011 at 10:03
Add a ment  | 

4 Answers 4

Reset to default 4

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)

  1. 暂无评论