加载本地JSON文件

本文讨论了在JavaScript(jQuery)中加载本地JSON文件时遇到的问题。内容包括使用Firebug发现的数据未定义错误,D3js处理本地JSON的解决方案,通过require.js加载文件的方法,以及利用FileReader和JSON.parser来读取用户选择的本地文件。
摘要由CSDN通过智能技术生成

本文翻译自:Loading local JSON file

I'm trying to load a local JSON file but it won't work. 我正在尝试加载本地JSON文件,但无法正常工作。 Here is my JavaScript code (using jQuery: 这是我的JavaScript代码(使用jQuery:

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

The test.json file: test.json文件:

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

Nothing is displayed and Firebug tells me that data is undefined. 什么都没有显示,Firebug告诉我数据未定义。 In Firebug I can see json.responseText and it is good and valid, but it's strange when I copy the line: 在Firebug中,我可以看到json.responseText ,它很好且有效,但是当我复制该行时很奇怪:

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

in Firebug's console, it works and I can access data. 在Firebug的控制台中,它可以正常工作,并且我可以访问数据。

Anyone have a solution? 有人有解决办法吗?


#1楼

参考:https://stackoom.com/question/UpAx/加载本地JSON文件


#2楼

Recently D3js is able to handle local json file. 最近, D3js能够处理本地json文件。

This is the issue https://github.com/mbostock/d3/issues/673 这是问题https://github.com/mbostock/d3/issues/673

This is the patch inorder for D3 to work with local json files. 这是D3与本地json文件一起使用的补丁程序。 https://github.com/mbostock/d3/pull/632 https://github.com/mbostock/d3/pull/632


#3楼

I had the same need (to test my angularjs app), and the only way I found is to use require.js: 我也有相同的需求(以测试我的angularjs应用程序),而我发现的唯一方法是使用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 有关使用nodejs读取文件的更多信息: http ://docs.nodejitsu.com/articles/file-system/how-to-read-files-in-nodejs

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


#4楼

Found this thread when trying (unsuccessfully) to load a local json file. 尝试(未成功)加载本地json文件时找到此线程。 This solution worked for me... 这个解决方案为我工作...

function load_json(src) {
  var head = document.getElementsByTagName('head')[0];

  //use class, as we can't reference by id
  var element = head.getElementsByClassName("json")[0];

  try {
    element.parentNode.removeChild(element);
  } catch (e) {
    //
  }

  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = src;
  script.className = "json";
  script.async = false;
  head.appendChild(script);

  //call the postload function after a slight delay to allow the json to load
  window.setTimeout(postloadfunction, 100)
}

... and is used like this... ...并以这种方式使用...

load_json("test2.html.js")

...and this is the <head> ... ...这是<head> ...

<head>
  <script type="text/javascript" src="test.html.js" class="json"></script>
</head>

#5楼

If you want to let the user select the local json file (anywhere on the filesystem), then the following solution works. 如果要让用户选择本地json文件(文件系统上的任何位置),则可以使用以下解决方案。

It uses uses FileReader and JSON.parser (and no jquery). 它使用FileReader和JSON.parser(并且没有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/ 这是FileReader的一个很好的介绍: http ://www.html5rocks.com/en/tutorials/file/dndfiles/


#6楼

$.ajax({
       url: "Scripts/testingJSON.json",
           //force to handle it as text
       dataType: "text",
            success: function (dataTest) {

                //data downloaded so we call parseJSON function 
                //and pass downloaded data
                var json = $.parseJSON(dataTest);
                //now json variable contains data in json format
                //let's display a few items
                $.each(json, function (i, jsonObjectList) {
                for (var index = 0; index < jsonObjectList.listValue_.length;index++) {
                      alert(jsonObjectList.listKey_[index][0] + " -- " + jsonObjectList.listValue_[index].description_);
                      }
                 });


             }
  });
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值