Access json value using JavaScript object notation

后端 未结 4 804
囚心锁ツ
囚心锁ツ 2021-01-28 18:34

I am unable to access a json value

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


        
相关标签:
4条回答
  • 2021-01-28 19:04

    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 讨论(0)
  • 2021-01-28 19:05

    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.

    0 讨论(0)
  • 2021-01-28 19:09

    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?

    0 讨论(0)
  • 2021-01-28 19:14

    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

    0 讨论(0)
提交回复
热议问题