gpt4 book ai didi

jquery - 如何解析 JSON 文件并查找特定键然后返回值?

转载 作者:行者123 更新时间:2023-12-01 04:50:59 25 4
gpt4 key购买 nike

这里是 JSON 新手。我正在尝试从 JSON 文件中查找特定值。基本上,我有一个搜索框,用户可以从自动完成下拉列表中的现有“名称”列表中选择“名称”(请参阅​​ jSON)。想法是返回输入的“name”对应的“url”值。

JSON(文档.json):

[
{ "tag": "Tutorial", "name": "Using Cloud", "url": "http://example.com/staff/doc/platform_training/index.html" },
{ "tag": "Tutorial", "name": "Help Tutorials", "url": "http://example.com/mason/staff/doc/tutorials/help/agent.html" },
{ "tag": "Tutorial", "name": "Big Stuff", "url": "http://example.com/mason/staff/doc/tutorials/orientation.html" }

]

jQuery:

        $('.livesearch').keypress(function (e) {
if (e.which == 13) {
searchTerm = $("#search").val();
// return the "url" based on the "searchTerm", which is basically the "name" key in the JSON file
}

});


function readJSON(searchTerm) {
$.getJSON( "json/docs.json", function( data ) {
$.each( data, function( key, val ) {
//
});
});

}

HTML:

<input class="livesearch" type="text" placeholder="Enter your search terms here" id="search" />

最佳答案

设置 searchTerm 后,调用 readJSON(searchTerm) 函数,然后在回调中执行以下操作:

var url = "";
for (var i = 0; i < data.length; i++) {
if (data[i].hasOwnProperty("name")) {
if (data[i].name == searchTerm) {
url = data[i].name;
break; //bye bye for loop
}
}
}

//do stuff

关于jquery - 如何解析 JSON 文件并查找特定键然后返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20107155/

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