How to include and manipulate local JSON file?

Asked

Viewed 7,563 times

4

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’m finding it very ugly to have it inside the code, I built this first one to see if it worked, even because this JSON will have almost 2000 items.

So I saved my JSON in 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);
});

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

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

Continuing the answers given, some questions arose 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 is presenting 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 to where the JSON file is, is correct.

Another question that came to me, where I fit the forEach?

  • Using some lib or js only?

  • I am using jQuery, Select2 and Bootstrap.

  • How do I edit my question?

  • There is an edit button below the tags that opens here Alexandre

  • I don’t understand why he says it’s not compatible, the way is right.

  • You should be using a local server, such as Wamp or Xampp. So this with the error Cross origin.

  • I understand, but do I need to use a local server for any algorithm? I mean, the idea of the program I’m working on is to be small! It doesn’t make sense to put a Wamp just to generate good programming practice.. At least that’s what I think.

Show 2 more comments

4 answers

3

With pure javascript you can read using Xmlhttprequest (yes, to read JSON). First create a file .json 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 function $.getJSON:

// 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
});
  • Using the Xmlhttprequest example, it also appears: Failed to load file://C:/Users/Alexandre/Desktop/Project%20Colet%C3%A2nea/New/js/carros.json: Cross origin requests are only supported for Protocol schemes: http, data, Chrome, Chrome-Extension, https.

3


In case you didn’t want to use JQuery 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 library jquery you should include the library:

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

And after loading the page you can access the file through the method getJSON():

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

  • Funny that for me is giving the following error in the console Uncaught TypeError: Cannot read property 'nomedavariavel' of null and even then leaves the value of the variable just below. How can be giving error and at the same time returning the value?

  • Sorry it took so long, I can’t tell you without seeing your code. Try to open a new question in stackoverflow with it, anything sends her link here and I try to help you.

  • Caique Romero I did it in a way that worked here: function loadJSON(url, callback) {&#xA; let xobj = new XMLHttpRequest();&#xA; xobj.overrideMimeType('application/json');&#xA; xobj.open('GET', url, true);&#xA; xobj.onreadystatechange = () => {&#xA; if (xobj.readyState == 4 && xobj.status == '200') callback(xobj.responseText);&#xA; };&#xA; xobj.send(null);&#xA;}

1

The reply sent by all are correct, what was not cited and what 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 was stopped, I thank everyone who participated and gave attention, unfortunately I will look for if there is way to work without the server, because in my case it is impractical, otherwise, I will keep the JSON inside my file same. Thank you very much.

-1

Example:

const fs = require('fs')

const produto = {
    nome: 'Produto',
    preco: 1249.99,
    desconto: 0.15
}

fs.writeFile(__dirname + '/arquivoGerado.json', JSON.stringify(produto), err => {
    console.log(err|| 'Arquivo salvo!')
})
  • Consider including a brief explanation of your response.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.