如何在javascript中获取数组内的json值
我有这个data.json文件,我需要得到“hashtags”的值,因为我的文件中有10000个json数据,所以我只包括重要的一个如何在javascript中获取数组内的json值,javascript,json,Javascript,Json,我有这个data.json文件,我需要得到“hashtags”的值,因为我的文件中有10000个json数据,所以我只包括重要的一个 var data = [ { "favorite_count": 0, "entities": { "hashtags": [ { "text": "Hope", "indices": [ 0,
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
]
}
]
}
}
]
所以我这里有一个hashtags,我只想得到文本,如果它是空的,它不会得到任何东西。。我无法获取值,也不知道如何迭代,因为我对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;
}
您可以使用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;
}
我省略了一些验证,但是如果每个主要对象都有实体和hashtags属性,那么应该不会有任何问题我认为您需要使用
JSON.parse(data)
解析JSON。太好了!JSON是JavaScript对象表示法的不足。。因此,这个名称意味着它被设计为使用JavaScript进行操作