gpt4 book ai didi

javascript - 如何在javascript中获取数组中的json值

转载 作者:行者123 更新时间:2023-11-30 17:10:35 24 4
gpt4 key购买 nike

我有这个 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;
}

最佳答案

你可以使用 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;
}

我省略了一些验证,但如果每个主要对象都具有entitieshashtags 属性,那应该没有任何问题

关于javascript - 如何在javascript中获取数组中的json值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27096672/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com