Loading local JSON file

I'm trying to load a local JSON file but it won't work. Here is my JavaScript code (using jQuery:

var json = $.getJSON("test.json");
var data = eval("(" +json.responseText + ")");
document.write(data["a"]);

The test.json file:

{"a" : "b", "c" : "d"}

Nothing is displayed and Firebug tells me that data is undefined. In Firebug I can see json.responseText and it is good and valid, but it's strange when I copy the line:

 var data = eval("(" +json.responseText + ")");

in Firebug's console, it works and I can access data.

Anyone have a solution?


$.getJSON是异步的,所以你应该这样做:

$.getJSON("test.json", function(json) {
    console.log(json); // this will show the info it in firebug console
});

I had the same need (to test my angularjs app), and the only way I found is to use require.js:

var json = require('./data.json'); //(with path)

note: the file is loaded once, further calls will use the cache.

More on reading files with nodejs: http://docs.nodejitsu.com/articles/file-system/how-to-read-files-in-nodejs

require.js: http://requirejs.org/


If you want to let the user select the local json file (anywhere on the filesystem), then the following solution works.

It uses uses FileReader and JSON.parser (and no jquery).

<html>
<body>

<form id="jsonFile" name="jsonFile" enctype="multipart/form-data" method="post">

  <fieldset>
    <h2>Json File</h2>
     <input type='file' id='fileinput'>
     <input type='button' id='btnLoad' value='Load' onclick='loadFile();'>
  </fieldset>
</form>


<script type="text/javascript">

  function loadFile() {
    var input, file, fr;

    if (typeof window.FileReader !== 'function') {
      alert("The file API isn't supported on this browser yet.");
      return;
    }

    input = document.getElementById('fileinput');
    if (!input) {
      alert("Um, couldn't find the fileinput element.");
    }
    else if (!input.files) {
      alert("This browser doesn't seem to support the `files` property of file inputs.");
    }
    else if (!input.files[0]) {
      alert("Please select a file before clicking 'Load'");
    }
    else {
      file = input.files[0];
      fr = new FileReader();
      fr.onload = receivedText;
      fr.readAsText(file);
    }

    function receivedText(e) {
      let lines = e.target.result;
      var newArr = JSON.parse(lines); 
    }
  }
</script>

</body>
</html>

Here is a good intro on FileReader: http://www.html5rocks.com/en/tutorials/file/dndfiles/

链接地址: http://www.djcxy.com/p/27558.html

上一篇: 阻止RequireJS缓存所需的脚本

下一篇: 加载本地JSON文件