2015-02-11 141 views
0

請幫助導致了JSON陣列 我嘗試的標題:打印數組?

(function (jQuery){ 
    var json = { 
     "news": [{ 
      "img": "http://static3.www.net/img/300x300/2257740.jpeg", 
      "title": "qwerty1", 
      "url": "http://news.net.www.ru/newdata/adclick?ad=674134&bl=80802&ct=adpreview&st=16&in=YK2NFgCJu2FWSQoAjkkKAIhJCgBhSQoAfkkKAGJJCgA%3D&ag=19", 
      "id": "674134" 
     }, { 
      "img": "http://static5.www.net/img/300x300/2257778.jpeg", 
      "title": "qwerty2", 
      "url": "http://news.net.www.ru/newdata/adclick?ad=674190&bl=80802&ct=adpreview&st=16&in=YK2NFgCJu2FWSQoAjkkKAIhJCgBhSQoAfkkKAGJJCgA%3D&ag=19", 
      "id": "674190" 
     }, { 
      "img": "http://static3.www.net/img/300x300/2257776.jpeg", 
      "title": "qwerty3", 
      "url": "http://news.net.www.ru/newdata/adclick?ad=674184&bl=80802&ct=adpreview&st=16&in=YK2NFgCJu2FWSQoAjkkKAIhJCgBhSQoAfkkKAGJJCgA%3D&ag=19", 
      "id": "674184" 
     }, { 
      "img": "http://static2.www.net/img/300x300/2257748.jpeg", 
      "title": "qwerty4", 
      "url": "http://news.net.www.ru/newdata/adclick?ad=674145&bl=80802&ct=adpreview&st=16&in=YK2NFgCJu2FWSQoAjkkKAIhJCgBhSQoAfkkKAGJJCgA%3D&ag=19", 
      "id": "674145" 
     }, { 
      "img": "http://static1.www.net/img/300x300/2257766.jpeg", 
      "title": "qwerty5", 
      "url": "http://news.net.www.ru/newdata/adclick?ad=674174&bl=80802&ct=adpreview&st=16&in=YK2NFgCJu2FWSQoAjkkKAIhJCgBhSQoAfkkKAGJJCgA%3D&ag=19", 
      "id": "674174" 
     }, { 
      "img": "http://static3.www.net/img/300x300/2257750.jpeg", 
      "title": "qwerty6", 
      "url": "http://news.net.www.ru/newdata/adclick?ad=674146&bl=80802&ct=adpreview&st=16&in=YK2NFgCJu2FWSQoAjkkKAIhJCgBhSQoAfkkKAGJJCgA%3D&ag=19", 
      "id": "674146" 
     }] 
    } 

    //console.log(JSON.parse(json)); 

    jQuery.each(JSON.parse(json), function(idx, obj) { 
     alert(idx + '__' + obj.news.title); 
    }); 
})($); 

結果,控制檯會顯示以下錯誤消息:

Uncaught SyntaxError: Unexpected token o

你可以看到在線版的代碼jsfiddle

+1

1.您缺少';'你的對象收盤'}'後。 2.你不需要解析這個json,因爲它已經是一個對象,所以這將成爲一個問題。 http://jsfiddle.net/x8dwjbj9/6/ – prodigitalson 2015-02-11 18:02:15

+1

'JSON.parse'將字符串轉換爲對象,'JSON.stringify'將對象轉換爲字符串。您正試圖將對象轉換爲具有函數的函數,該函數將字符串作爲輸入。 – 2015-02-11 18:03:35

+0

你的'json'變量是一個JavaScript對象。這是***不是*** JSON。 JSON是數據的*字符串表示*。如果它不是字符串,那不是JSON。 – 2015-02-11 18:04:47

回答

2

更改您的最後一點 -

jQuery.each(json.news, function(idx, obj) { 
      alert(idx + '__' + obj['title']); 
     }); 
    })($); 

你必須遍歷JSON

新聞
0

它已被解析。所以JSON.parse會拋出一個錯誤。修復是JSON.parse(json)應該是簡單的json

希望這會有所幫助。

+1

你應該添加'if(json.hasOwnProperty(i))' – 2015-02-11 18:04:41

+0

@JanLegner對不起,實際上$ .each也支持對象迭代。我錯過了。所以我刪除了該行。 – UndefinedN 2015-02-11 18:06:10