How to access @attr value in JSON using jQuery

I work with last.fm api to get artist images, and I get JSON results where I need to check @attr value. Unfortunately, I cannot access this value. The results look something like this:

{"image":[{
    "url":"http:\/\/www.last.fm\/music\/Undefined\/+images\/3040021",
    "format":"jpg",
    "sizes":{"size":{"#text":"http:...jpg","name":"original","width":"397","height":"397"},{"#text":"http:...jpg","name":"large","width":"126","height":"126"},]},
    "@attr":{"official":"yes"}}

this is the last value i cannot get ...

any ideas?

I tried ['@attr'] and it didn't seem to work, it returned only undefined.

I do $ .each (obj.image, function () {}) - and inside I successfully get this.url, this.format, etc. - but I'm out of luck with this ['@attr']

+5
source share
2 answers

Use the operator binding operator :

var value = obj[0]['@attr'];

official:

value.official;

obj[0]['@attr']['official'];

obj[0]['@attr'].official;

: , JSON, , JSON , JSONLint.

, - :

var obj = {
  "image": [{
    "url": "http:\/\/www.last.fm\/music\/Undefined\/+images\/3040021",
    "format": "jpg",
    "sizes": [{
      "#text": "http:...jpg",
      "name": "original",
      "width": "397",
      "height": "397" 
    },
    {
      "#text": "http:...jpg",
      "name": "large",
      "width": "126",
      "height": "126" 
    } 
    ],
    "@attr": {
      "official": "yes" 
    } 
  }]
};

JSON :

$.each(obj.image, function () {
  alert(this['@attr'].official);
});
+9

. JSON, - , , , .

{ /* no matching end */
    "images": [ /* no matching end */
        {
            "url":"http:\/\/www.last.fm\/music\/Undefined\/+images\/3040021",
            "format":"jpg",
            "sizes": { /* should this be an array instead? */
                "size": {
                  "#text":"http:...jpg",
                  "name":"original",
                  "width":"397",
                  "height":"397"
                },
                { /* missing key */
                  "#text":"http:...jpg",
                  "name":"large",
                  "width":"126",
                  "height":"126"
                }, /* trailing comma can cause parsing issues */
              ] /* no matching start */
            },
            "@attr": { "official":"yes" }
        }
+2

All Articles