javascript 如何在 JSON 文件中搜索?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34255181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to search in JSON file?
提问by Caspert
How could I create a search form that will search for the entered term inside a JSON file?
我如何创建一个搜索表单来搜索 JSON 文件中输入的术语?
So if the search term is equal to a title inside the location object, it should return that object info. If there is no match, give the user feedback that there are no items found
因此,如果搜索词等于位置对象内的标题,则应返回该对象信息。如果没有匹配,给用户反馈没有找到项目
I created a search input:
我创建了一个搜索输入:
<form action="" method="get">
<input id="search" type="text" placeholder="Search term">
<input type="submit" class="button">
</form>
My JSON looks like this:
我的 JSON 如下所示:
{
"title": "Locations",
"locations": [
{
"title": "New York",
"url": "api/newyork.js"
},{
"title": "Dubai",
"url": "api/dubai.js"
},{
"title": "Netherlands",
"url": "api/netherlands.js"
},{
"title": "Lanzarote",
"url": "api/lanzarote.js"
},{
"title": "Italy",
"url": "api/italy.js"
}
]
}
Update:
更新:
I came up with the following, using jQuery:
我想出了以下内容,使用 jQuery:
$("#search").change(function() {
var arrival = $(this).val();
$.getJSON( "api/videoData.js")
.done(function(data) {
// update your ui here
console.dir(data.pages);
var dataArr = data.pages;
// Iterate over each element in the array
for (var i = 0; i < dataArr.length; i++){
// look for the entry with a matching `code` value
if (dataArr[i].title == arrival){
// we found it
console.log(dataArr[i].title);
} else {
console.log('Houston, we have a problem');
}
}
}).fail(function(data) {
// handle error here
console.log('no results found');
});
});
This is working, only it should be entered exactly as stored in the JSON.
So when you search for "Italy" and you use lowercase type, it will not find the object. Also it will not give any entries when you search for example: ne
. I would like to get Netherlands and New York as search results.
这是有效的,只是应该完全按照 JSON 中存储的方式输入它。因此,当您搜索“意大利”并使用小写类型时,它不会找到该对象。它也不会在您搜索时提供任何条目,例如:ne
。我想将荷兰和纽约作为搜索结果。
回答by trincot
Here is a snippet that demonstrates how the lookup could be done. It only loads the JSON once. I have included the test data for when the JSON request fails, which it will in this demo. At every change of the input value a short list of matches is shown in a div
below the input
. The submit button is not included, as the search is immediate.
这是一个演示如何完成查找的片段。它只加载一次 JSON。我已经包含了 JSON 请求失败时的测试数据,它会在这个演示中。在输入值的每一个变化示于一个比赛的短列表div
如下input
。不包括提交按钮,因为搜索是即时的。
Try it.
试试看。
// testData is defined for demo only. Can be removed
var testData = [
{
"title": "New York",
"url": "api/newyork.js"
},{
"title": "Dubai",
"url": "api/dubai.js"
},{
"title": "Netherlands",
"url": "api/netherlands.js"
},{
"title": "Lanzarote",
"url": "api/lanzarote.js"
},{
"title": "Italy",
"url": "api/italy.js"
}
];
// Variable to hold the locations
var dataArr = {};
// Load the locations once, on page-load.
$(function() {
$.getJSON( "api/videoData.js").done(function(data) {
window.dataArr = data.pages;
}).fail(function(data) {
console.log('no results found');
window.dataArr = testData; // remove this line in non-demo mode
});
});
// Respond to any input change, and show first few matches
$("#search").on('keypress keyup change input', function() {
var arrival = $(this).val().toLowerCase();
$('#matches').text(!arrival.length ? '' :
dataArr.filter(function(place) {
// look for the entry with a matching `code` value
return (place.title.toLowerCase().indexOf(arrival) !== -1);
}).map(function(place) {
// get titles of matches
return place.title;
}).join('\n')); // create one text with a line per matched title
});
// submit button is not needed really
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="search" type="text" placeholder="Search term">
<div id="matches" style="height:70px; overflow-y:hidden; white-space:pre"></div>
回答by Richard
The solution has a few steps, let us know which step you can't do:
解决方案有几个步骤,让我们知道您不能执行的步骤:
- Call a JS function when the user clicks the button
- Read the file from disk on the server into a JS variable in the browser
- Use lodash.js to get the url from the JS variable for the search term
- Display results to the user
- 当用户点击按钮时调用一个 JS 函数
- 将服务器上磁盘中的文件读入浏览器中的JS变量中
- 使用 lodash.js 从 JS 变量中获取搜索词的 url
- 向用户显示结果
But taking a stab at the simplest answer, the way I'd do it:
但是尝试一下最简单的答案,我会这样做:
Load your JSON file with the page, like any Javascript file. Load lodash.js.
将您的 JSON 文件与页面一起加载,就像任何 Javascript 文件一样。加载 lodash.js。
Call your JSON file towns.js and make it look like this:
调用您的 JSON 文件 towns.js 并使其看起来像这样:
var cities =
{
"title": "Locations",
"locations":
[
{
"title": "New York",
"url": "api/newyork.js"
},
{
"title": "Dubai",
"url": "api/dubai.js"
}
]
}
And then your HTML is something like this:
然后你的 HTML 是这样的:
<input type="" class="button" onclick='go()'>
<script src='towns.js' />
<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.min.js' />
<script>
function go()
{
var name = document.getElementById('search').value;
var result = _.find(cities.locations, {'title': name});
if (!result)
window.alert('Nothing found');
else
window.alert('Go to ' + result.url);
}
<script>
回答by Miguel
As you said in your update with this code:
正如您在使用此代码的更新中所说:
So when you search for "Italy" and you use lowercase type, it will not find the object. Also it will not give any entries when you search for example: ne. I would like to get Netherlands and New York as search results.
因此,当您搜索“意大利”并使用小写类型时,它不会找到该对象。当您搜索例如:ne 时,它也不会给出任何条目。我想将荷兰和纽约作为搜索结果。
$("#search").change(function() { var arrival = $(this).val();
$("#search").change(function() { var到达 = $(this).val();
$.getJSON( "api/videoData.js", { arrivalDate: arrival })
.done(function(data) {
// update your ui here
console.dir(data.pages);
var dataArr = data.pages;
// Iterate over each element in the array
for (var i = 0; i < dataArr.length; i++){
// look for the entry with a matching `code` value
if (dataArr[i].title == arrival){
// we found it
console.log(dataArr[i].title);
} else {
console.log('Houston, we have a problem');
}
}
}).fail(function(data) {
// handle error here
console.log('no results found');
});
});
Replace this line:
替换这一行:
if (dataArr[i].title == arrival){
for
为了
if (dataArr[i].title.toLowerCase().contains(arrival.toLowerCase())){
And now it will match all the string that contains the string that you are searching...
现在它将匹配包含您正在搜索的字符串的所有字符串...
回答by RomanPerekhrest
If you intend your json file as static and not very huge one then you better load it at once on page load event(preventing sending the same requests dozens of times). Try this approach:
如果您打算将 json 文件作为静态文件而不是非常大的文件,那么您最好在页面加载事件中立即加载它(防止多次发送相同的请求)。试试这个方法:
var xhr = new XMLHttpRequest(),
locations = {};
xhr.overrideMimeType("application/json");
xhr.open('GET', 'locations.json', true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == "200") {
var content = JSON.parse(this.response),
locations_arr, i, count, title;
locations_arr = content['locations'];
for (i = 0, count = locations_arr.length; i < count; i++) {
title = locations_arr[i]['title'].toLowerCase();
locations[title] = locations_arr[i];
}
console.log(locations);
}
};
xhr.send(null);
Add some identifier to your form element (id="myForm"
) and 'name' attribute to your input field (name="search"
);
将一些标识符添加到您的表单元素 ( id="myForm"
) 并将“名称”属性添加到您的输入字段 ( name="search"
);
document.getElementById('myForm').onsubmit = function() {
var search_value = this.search.value.trim().toLowercase();
if (search_value && location[search_value]) {
console.log(location[search_value]);
} else {
alert("Object with specified title not found!");
}
// You must return false to prevent the default form behavior
return false;
}