2014-11-24 75 views
1

我有這個data.json文件,並且我需要獲取「hashtags」的值,它是10,000個json數據,因此我只包含重要的一個..如何在javascript中獲取數組中的json值

var data = 
[ 
{ 
    "favorite_count": 0, 
    "entities": { 
     "hashtags": [ 
      { 
       "text": "Hope", 
       "indices": [ 
        0, 
        5 
       ] 
      }, 
      { 
       "text": "USA", 
       "indices": [ 
        6, 
        10 
       ] 
      }, 
      { 
       "text": "Youth", 
       "indices": [ 
        11, 
        17 
       ] 
      }, 
      { 
       "text": "sex", 
       "indices": [ 
        51, 
        55 
       ] 
      }, 
      { 
       "text": "condoms", 
       "indices": [ 
        94, 
        102 
       ] 
      }, 
      { 
       "text": "STD", 
       "indices": [ 
        120, 
        124 
       ] 
      }, 
      { 
       "text": "HPV", 
       "indices": [ 
        135, 
        139 
       ] 
      } 
     ] 
    } 
}, 
{ 
    "favorite_count": 0, 
    "entities": { 
     "hashtags": [ 
      { 
       "text": "starbucks", 
       "indices": [ 
        3, 
        13 
       ] 
      } 
     ] 
    } 
    } 
] 

所以我在這裏有一個標籤,我只想得到文本,如果它是空的,它不會得到任何東西..我無法獲得值,我不知道如何迭代它因爲我不熟悉JSON ..這裏是我的代碼,在JavaScript中的方式

$(document).ready(function() 
{ 
    $("#hashtagBtn").click(function() 
    { 
     $("#theTweets").html(graphHashtag()); 
    }); 
}); 



function graphHashtag() 
{ 
    var getHashtags = []; 

    $.each(data, function(i, obj) 
    { 
     if(obj.hasOwnProperty("text") && data[i].lang == "en" && data[i].entities.hashtags != null) 
      getHashtags.push(obj.entities.hashtags[i].text); 
    }); 

    return getHashtags; 
} 
+0

我想你需要用'JSON.parse(data)'解析JSON。 – esswilly 2014-11-24 01:59:31

回答

2

你可以使用這種類型的JavaScript SK ...沒有jQuery的包裝需要

function graphHashtag() 
{ 
    var tags= []; 

    for (var i in data) 
    { 
     // data[i] is an object 

     for (var j in data[i].entities.hashtags) 
     { 
      var text = data[i].entities.hashtags[j].text; 

      if (text) tags.push(text); 
     } 
    } 
    return tags; 
} 

我省略了一些驗證,但如果每一個主要目標將有實體哈希標籤性能不應該有任何問題

+0

非常感謝你解決了我的問題:) – user14 2014-11-24 02:45:47

+0

太棒了! ** JSON **是JavaScript Object Notation的缺陷,所以它的名字暗示它被設計爲使用JavaScript進行操作 – ymz 2014-11-24 07:42:21

相關問題