Insert JSON file into JSFiddle

3

I'm trying to solve a question with a plugin that uses jQuery but I do not know how to insert a JSON file into JSFiddle.

This JSON is a string and comes from a .json file.

    
asked by anonymous 06.12.2015 / 08:19

1 answer

3

It depends a little on where you are going to get JSON.

If it's a string you can paste it directly into the JavaScript space:

var str = '{"objeto": {"foo":"bar"}}';
var json = JSON.parse(str);

If it's a larger file, I usually put it in an ajax script:

function buscaJSON(url, cb) {
  var request = new XMLHttpRequest();
  request.open('GET', url, true);
  request.onload = function() {
    if (request.status >= 200 && request.status < 400) {
      var data = JSON.parse(request.responseText);
      cb(null, data);
    } else {
      cb('Error: ' + request.responseText);
    }
  };
  request.onerror = function() {
    cb('Unknown error');
  };

  request.send();
}

buscaJSON('https://rawgit.com/SergioCrisostomo/version-files/master/json_example.json', function(err, json) {
  alert(JSON.stringify(json, null, 4));
});

link

    
06.12.2015 / 08:35