How to Include and manipulate local JSON file?

3

I use JSON data to create the <options> of a <select> :

jsonOptions.forEach(function(item) {                
  var option = document.createElement('option');
  option.text = item.description;
  option.value = item.product;
  dataList.appendChild(option);           
});

But I find it very ugly to have this inside the code, I mounted this one first to see if it worked, even because this JSON will have almost 2000 items.

So I saved my JSON to a separate file and tried to include an external file as follows:

[ 
    {"description": "Carro 1"},
    {"description": "Carro 2", "product": "4"},
    {"description": "Carro 3", "product": "4"},
    {"description": "Carro 4", "product": "4"},
    {"description": "Carro 5", "product": "4"},
    {"description": "Carro 6", "product": "4"}
]

$.getJSON("js/carros.json", function(item) {
  var option = document.createElement('option');
  option.text = item.description;
  option.value = item.product;
  dataList.appendChild(option);
});

In addition to the correct way to save the file and call it, another question I have is with the jQuery library call.

Do I need to call it inside the JavaScript that I am running the code or the fact that it is present there in the HTML means that it has already been loaded?

Continuing the answers given, some questions have arisen regarding the algorithm.

$.getJSON('js/carros.json', function(err, data) {
  if (err !== null) {
    console.log('Ocorreu um erro' + err);
  } else {
    alert("chegou aqui!")
    console.log(data);
  }
});

I am using this code, and it is displaying the error in the Console:

jquery-2.1.0.js:8556 Failed to load file:///C:/Users/Alexandre/Desktop/Projeto%20Colet%C3%A2nea/New/js/carros.json: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

Checking the path where the JSON file is, is correct.

Another question that came up, where do I fit the forEach ?

    
asked by anonymous 12.01.2018 / 13:28

3 answers

1

If you did not want to use JQuery you can access the file using XMLHttpRequest () :

var getJSON = function(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'json';
    xhr.onreadystatechange = function() {
      var status = xhr.status;
      if (status === 200) { 
        //Callback caso de tudo certo
        callback(null, xhr.response);
      } else {
        //Callback caso de algum erro
        callback(status, xhr.response);
      }
    };
    xhr.send();
};

//Utilizando o método
getJSON('SeuArquivo.json', function(err, data) {
  if (err !== null) {
    console.log('Ocorreu um erro' + err);
  } else {
    //Aqui você manipula os dados e pode percorrer e jogar no HTML 
    //da forma que achar mais adequada.
    console.log(data);
  }
});

If you wanted to use the jquery library you should include the library:

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

Andafterloadingthepageyoucanaccessthefileusingthe getJSON () method:

//OnLoad
$(function(){

  $.getJSON("SeuArquivo.json", function(data) {
    //Aqui você manipula os dados e pode percorrer e jogar no HTML 
    //da forma que achar mais adequada.
      console.log(data); 
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
12.01.2018 / 13:43
2

With pure javascript one can read using XMLHttpRequest (yes, to read JSON). First create a .json file to use one of the functions. Example:

var xmlhttp = new XMLHttpRequest();
var url = "meu_json.json"; // caminho do arquivo

xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var myArr = JSON.parse(this.responseText);
        handle(myArr);
    }
};
xmlhttp.open("GET", url, true);
xmlhttp.send();

function handle(arr) {
    // forEach aqui para criar o select
}

Or more easily with jQuery you can use the $ .getJSO N:

// onde ajax/meu_json.json é o caminho do arquivo
$.getJSON( "ajax/meu_json.json", function( data ) {
  // forEach aqui para criar o select a partir de data
});
    
12.01.2018 / 13:40
0

The reply sent by everyone is correct, which was not quoted and that is the problem of my code is that I do not use a local server.

This is an algorithm model that solves the problem for who has the local server as Wamp.

$.getJSON('js/carros.json', function(err, data) {
  if (err !== null) {
    console.log('Ocorreu um erro' + err);
  } else {
    alert("chegou aqui!")
    console.log(data);
  }
});

I will close the topic because it is stopped, I thank everyone who participated and gave attention, unfortunately I will look for if there is a way to work without the server, because in my case it is impractical, otherwise I will keep JSON within my same file. Many thanks.

    
12.01.2018 / 17:48