我有这个data.json文件,我需要获取" hashtags"的值。它在我的文件中是10,000个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 :(得分:2)
你可以使用javascript进行这类任务......不需要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;
}
我省略了一些验证,但如果每个主要对象都有实体和主题标签属性,那么应该没有任何问题