【问题标题】:How to search in JSON file?如何在 JSON 文件中搜索?
【发布时间】:2015-12-13 19:15:42
【问题描述】:

如何创建一个搜索表单来搜索 JSON 文件中输入的术语?

因此,如果搜索词等于位置对象内的标题,它应该返回该对象信息。如果没有匹配,给用户反馈没有找到项目

我创建了一个搜索输入:

    <form action="" method="get">               
         <input id="search" type="text" placeholder="Search term">
         <input type="submit" class="button">
   </form>

我的 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"
        }

    ]
}

更新:

我想出了以下,使用 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');
            });

        });

这是有效的,只是它应该完全按照存储在 JSON 中的方式输入。 因此,当您搜索“意大利”并使用小写类型时,它不会找到该对象。此外,当您搜索时,它不会提供任何条目:ne。我想将荷兰和纽约作为搜索结果。

【问题讨论】:

  • 您自己尝试过任何 javascript 吗?如果是,请提供代码
  • @depperm,还没有。当用户单击提交按钮时,我不知道如何获取该值,而不是搜索该术语..
  • 对于小写和部分匹配只需说:_.startsWith(dataArr[i].title.toLowerCase(),arrival.toLowerCase())
  • 为什么要通过arrivaldate URL参数传递搜索值?您是否打算传递在另一个输入中输入的日期?你能在你的问题中澄清这一点吗?
  • 感谢您的提及。我认为这不再是代码的一部分。我将其从代码中删除。

标签: javascript php json


【解决方案1】:

这是一个演示如何进行查找的 sn-p。它只加载一次 JSON。我已经包含了 JSON 请求失败时的测试数据,它将在这个演示中。每次更改输入值时,都会在div 下方的input 中显示一个简短的匹配列表。不包括提交按钮,因为搜索是即时的。

试试看。

// 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>

【讨论】:

    【解决方案2】:

    解决方案有几个步骤,让我们知道你不能做哪一步:

    1. 当用户点击按钮时调用一个JS函数
    2. 从服务器磁盘读取文件到浏览器的JS变量中
    3. 使用 lodash.js 从 JS 变量中获取搜索词的 url
    4. 向用户显示结果

    但是尝试最简单的答案,我会这样做:

    像任何 Javascript 文件一样,将您的 JSON 文件与页面一起加载。 加载 lodash.js。

    调用您的 JSON 文件 towns.js 并使其如下所示:

    var cities = 
    {
        "title":    "Locations",
        "locations":    
        [
            {
                "title":        "New York",
                "url":          "api/newyork.js"
            },
            {
                "title":        "Dubai",
                "url":          "api/dubai.js"
            }
        ]
    }
    

    然后你的 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>
    

    【讨论】:

    • 我在一秒钟前更新了我的答案,也许你可以帮助我。我现在就试试你的代码!
    【解决方案3】:

    如果您打算将您的 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);
    

    为您的表单元素添加一些标识符 (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;
      }
    

    【讨论】:

      【解决方案4】:

      正如您在使用此代码的更新中所说:

      因此,当您搜索“意大利”并使用小写类型时,它不会找到该对象。此外,当您搜索例如:ne 时,它​​不会给出任何条目。我想将荷兰和纽约作为搜索结果。

      $("#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');
              });
      
          });
      

      替换这一行:

      if (dataArr[i].title == arrival){
      

      if (dataArr[i].title.toLowerCase().contains(arrival.toLowerCase())){
      

      现在它将匹配包含您正在搜索的字符串的所有字符串...

      【讨论】:

      • 我应该用你修改后的代码替换哪一行?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-23
      • 1970-01-01
      • 2016-01-06
      • 2019-08-11
      • 2018-09-02
      • 2021-09-10
      相关资源
      最近更新 更多