Searching for data in JSON file

0

I need to get data in JSON, display it and search, so I developed this code, but I'm having trouble putting this data in an external file. How can I put this JSON in an external file, keeping the same current structure without using Jquery?

JavaScript code:

var content = document.getElementById("content");
var tmplItem = document.getElementById("templatePost");
var search = document.getElementById("search"); 

var database = [
    {
        "id": 1,
        "nome_jogo": "Jogo 1",
        "url_jogo": "jogos/url_do_jogo",
        "img": "nome_do_jogo.jpg",
        "img_alt": "Carregando...",
        "tags": "tags de busca"
    },
    {
        "id": 2,
        "nome_jogo": "Jogo 2",
        "url_jogo": "jogos/url_do_jogo",
        "img": "nome_do_jogo.jpg",
        "img_alt": "Carregando...",
        "tags": "tags de busca"
    }
];

function showItems(search) {
    const filteredData = database.filter(item =>
        item.tags.toLowerCase().includes(search)
        || item.nome_jogo.toLowerCase().includes(search)
    );
    filteredData.forEach(function (dataItem, indice) {
        var item = document.importNode(tmplItem.content, true);
        item.querySelector(".url").setAttribute("href", dataItem.url_jogo);
        item.querySelector(".img").setAttribute("src", dataItem.img);
        item.querySelector(".img").setAttribute("alt", dataItem.img_alt);
        item.querySelector(".title").textContent = dataItem.nome_jogo;
        content.appendChild(item);
    });
}

function clearItems() {
    content.innerHTML = '';
}

search.addEventListener('input', function (e) {
    const valueInput = e.target.value.toLowerCase();
    clearItems();
    showItems(valueInput);
});

showItems('');

HTML Code:

<input type="text" placeholder="Busca" id="search">

<section>
    <div class="container">
        <div class="row" id="content"></div>
    </div>
</section>

<template id="templatePost">
    <div class="col-md-2">
        <article>
            <a href="" class="url">
                <img src="" alt="" class="img"/>
                <div><h4 class="title"></h4></div>
            </a>
        </article>
    </div>
</template>
    
asked by anonymous 28.12.2018 / 19:02

1 answer

0

Well, if you want to get this array of objects and convert it to a valid .json file, you'll have to make the following changes because Json data has different formatting Javascript:

{"database": [
  {
    "id": 1,
    "nome_jogo": "Jogo 1",
    "url_jogo": "jogos/url_do_jogo",
    "img": "nome_do_jogo.jpg",
    "img_alt": "Carregando...",
    "tags": "tags de busca"
  },
  {
    "id": 2,
    "nome_jogo": "Jogo 2",
    "url_jogo": "jogos/url_do_jogo",
    "img": "nome_do_jogo.jpg",
    "img_alt": "Carregando...",
    "tags": "tags de busca"
  }
]}
  

After making the changes, save the file with the extension .json and you can do it normally.

     

A good online tool for testing valid Json formats is here .

    
28.12.2018 / 22:19