2013-01-11 2 views
0

Прошу прощения, если это может быть похоже на мой предыдущий вопрос. Почему поиск узла, который не существует в анализе JSON, приводит к сбою любого другого допустимого узла?разбор JSON для отсутствующих данных вызывает ошибку

json.track.wiki.summary causes all to error 
json.track.name is fine if used without the previous 

//JSON data 
{ 
    "track": { 
     "id": "434483410", 
     "name": "Written in the Stars", 
     "mbid": "", 
     "url": "http://www.last.fm/music/Tinie+Tempah+(Feat.+Eric+Turner)/_/Written+in+the+Stars", 
     "duration": "208000", 
     "streamable": { 
      "#text": "0", 
      "fulltrack": "0" 
     }, 
     "listeners": "108", 
     "playcount": "1523", 
     "artist": { 
      "name": "Tinie Tempah (Feat. Eric Turner)", 
      "mbid": "", 
      "url": "http://www.last.fm/music/Tinie+Tempah+(Feat.+Eric+Turner)" 
     }, 
     "toptags": "\n " 
    } 
} 

Последующий доступ к ошибкам для допустимых узлов. Устраните запрос на отсутствие данных, и последующий запрос будет работать. должен быть способ протестировать объект, прежде чем использовать его, чтобы он не удалял данные FUBAR.

Эти данные были бы ОК

//JSON Data 
{ 
"track": { 
    "id": "517047006", 
    "name": "Skyscraper", 
    "mbid": "a92f853d-ad6d-490e-a820-4cff9cc1f224", 
    "url": "http://www.last.fm/music/Demi+Lovato/_/Skyscraper", 
    "duration": "222000", 
    "streamable": { 
     "#text": "1", 
     "fulltrack": "0" 
    }, 
    "listeners": "114757", 
    "playcount": "1424456", 
    "artist": { 
     "name": "Demi Lovato", 
     "mbid": "faf4cefb-036c-4c88-b93a-5b03dd0a0e6b", 
     "url": "http://www.last.fm/music/Demi+Lovato" 
    }, 
    "album": { 
     "artist": "Demi Lovato", 
     "title": "Unbroken", 
     "mbid": "9c195a9b-2db4-4b63-9337-6d8152244742", 
     "url": "http://www.last.fm/music/Demi+Lovato/Unbroken", 
     "image": [{ 
      "#text": "http://userserve-ak.last.fm/serve/64s/69672054.png", 
      "size": "small" 
     }, { 
      "#text": "http://userserve-ak.last.fm/serve/126/69672054.png", 
      "size": "medium" 
     }, { 
      "#text": "http://userserve-ak.last.fm/serve/174s/69672054.png", 
      "size": "large" 
     }, { 
      "#text": "http://userserve-ak.last.fm/serve/300x300/69672054.png", 
      "size": "extralarge" 
     }], 
     "@attr": { 
      "position": "11" 
     } 
    }, 
    "toptags": { 
     "tag": [{ 
      "name": "pop", 
      "url": "http://www.last.fm/tag/pop" 
     }, { 
      "name": "ballad", 
      "url": "http://www.last.fm/tag/ballad" 
     }, { 
      "name": "female vocalists", 
      "url": "http://www.last.fm/tag/female%20vocalists" 
     }, { 
      "name": "inspirational", 
      "url": "http://www.last.fm/tag/inspirational" 
     }, { 
      "name": "demi lovato", 
      "url": "http://www.last.fm/tag/demi%20lovato" 
     }] 
    }, 
    "wiki": { 
     "published": "Sat, 20 Aug 2011 18:25:23 +0000", 
     "summary": "The Skyscraper Songfacts says: On November 1, 2010, Demi's publicist announced the Disney star had entered a treatment facility for " 
     physical and emotional issues, 
     " which was subsequently reported to include an eating disorder and self-cutting. Her first single since her stint in treatment finds the singer/actress finding strength in the wake of a fading relationship and it symbolizes her resilience in the face of her personal issues.", 
     "content": "The Skyscraper Songfacts says: On November 1, 2010, Demi's publicist announced the Disney star had entered a treatment facility for " 
     physical and emotional issues, 
     " which was subsequently reported to include an eating disorder and self-cutting. Her first single since her stint in treatment finds the singer/actress finding strength in the wake of a fading relationship and it symbolizes her resilience in the face of her personal issues.\n \nUser-contributed text is available under the Creative Commons By-SA License and may also be available under the GNU FDL." 
    } 
} 

}

+0

Вы используете var data = $ .parseJSON (source); ?. – MyStream

+0

Ваш второй набор данных недействителен JSON – Musa

+0

Да: var obj = jQuery.parseJSON (strLastFM); Я застрял с JSON, поскольку он исходит из Last.FM и будет отличаться от любого запроса. – hillcreative

ответ

2

ошибка не вызывает другой код на провал. При ошибках первой строки он прекращает выполнение, так что другой код никогда не будет достигнут.

Вы можете добавить что-то вроде этого:

if(json && json.track && json.track.wiki){ 
    // do something with json.track.wiki.summary 
} 
0

в случае, если ваши поля JSON не фиксированы, вы должны проверить их наличие в результате JSon. вы можете попробовать ниже код для делать то же самое:

if (typeof(json.track.wiki) != "undefined") 
{ 
//code for what to do with json here 
} 

ИЛИ

сделать функцию, как показано ниже, и передать элемент узла, чтобы проверить его существование (Preferred)

function isExists(node) { 
    if (node== undefined) 
     return "" 
    else 
     return node 
} 

// и вызов это так

var nodevalue=isExists(json.track.wiki) 

, делая это, вы убедитесь, что конкретный узел существует до его использования. так что более поздний код также выполняется правильно.

вы можете получить код ошибки выше. так что не забудьте исправить !!

Смежные вопросы