Ben Ben - 4 months ago 18
JSON Question

jQuery search JSON for a particular value

I'm new to jQuery and JSON (when you look at my code below you'll quickly see how new I am).

I've got a JSON file and I want to allow users to input a search term (which will be a key in JSON file)) and have the corresponding JSON value be displayed on the web page.

I've searched this forum and the web and, using examples I've found, I've hacked together a script and some HTML but, surprise!, it's not working. I have a rough idea of what the script is doing but I'm finding it very difficult to sort out what is wrong.

Hoping someone can help.

HTML:

<input type="search" name="search" id="search">


jQuery:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<script>

$('#search').keyup(function() {
var searchField = $('#search').val();
var myExp = new RegExp(searchField, "i");
$.get('products.json', function(data) {
var output = '<ul class="searchresults">';
$(data).find(searchField).each(function(index, value){
var val = value.firstChild.nodeValue;
if ((val.search(myExp) != -1)) {
output += '<li>' + val + '</li>';
}
});
output += '</ul>';
$('#result').html(output);
});
});

</script>


JSON (products.json)(The JSON file will be longer than this. I've simplified it):

{"colors":[
{"A":"red"},
{"B":"green"},
{"C":"blue"}
]}


So, if a user types 'B' into the HTML searchfield, I want 'green' to be displayed on the web page.

Answer

Please try this:

$('#search').keyup(function() {
    var searchField = $('#search').val();
    $.getJSON('https://api.myjson.com/bins/59t77', function(data) {
    console.log(data);
        var output = '<ul class="searchresults">';
        $.each(data.colors, function(k, obj) {
            if(obj[searchField]) {
                output += '<li>' + obj[searchField] + '</li>';
            }
        });
        output += '</ul>';
        $('#result').html(output);
    });  
});

With some more explanation on your specific issue, I may be able to assist you in better alternatives.

Demo: https://jsfiddle.net/iRbouh/0z228fya/