我试图加载一个本地JSON文件,但它不会工作。下面是我的JavaScript代码(使用jQuery):

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

测试。json文件:

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

什么也没有显示,Firebug告诉我数据是未定义的。在Firebug中我可以看到json。responseText和它是好的和有效的,但它是奇怪的,当我复制一行:

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

在Firebug的控制台中,它可以工作,我可以访问数据。

有人有办法吗?


当前回答

我很惊讶从es6导入没有提到(使用小文件)

从“。/test.json”导入测试

Webpack 2<使用json加载器作为.json文件的默认值。

https://webpack.js.org/guides/migrating/#json-loader-is-not-required-anymore

打字稿:

import test from 'json-loader!./test.json';

TS2307 (TS)无法找到模块“json-loader!./suburbs.json”

为了让它工作,我必须首先声明模块。我希望这能为某人节省几个小时的时间。

declare module "json-loader!*" {
  let json: any;
  export default json;
}

...

import test from 'json-loader!./test.json';

如果我试图从json-loader中忽略loader,我从webpack中得到以下错误:

突破性变化:不再允许省略'-loader'后缀 当使用加载器时。 你需要指定'json-loader'而不是'json', 看到https://webpack.js.org/guides/migrating/ automatic-loader-module-name-extension-removed

其他回答

从头开始添加到JSON文件中

var object1 = [

在最后

]

保存它

然后用纯js加载它

<script type="text/javascript" src="1.json"></script>

现在你可以使用它作为object1 -它已经加载!

完美的工作在Chrome和没有任何额外的库

function readTextFile(srcfile) {
        try { //this is for IE
            var fso = new ActiveXObject("Scripting.FileSystemObject");;
            if (fso.FileExists(srcfile)) {
                var fileReader = fso.OpenTextFile(srcfile, 1);
                var line = fileReader.ReadLine();
                var jsonOutput = JSON.parse(line); 
            }

        } catch (e) {

        }
}

readTextFile("C:\\Users\\someuser\\json.txt");

我所做的是,首先,从network选项卡,记录服务的网络流量,从响应体,复制并保存json对象到本地文件中。然后用本地文件名调用函数,你应该能够在上面的jsonOutout中看到json对象。

如果您想让用户选择本地json文件(文件系统上的任何位置),那么下面的解决方案是可行的。

它使用FileReader和JSON。解析器(没有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>

这里有一个很好的FileReader介绍:http://www.html5rocks.com/en/tutorials/file/dndfiles/

$.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_);
                      }
                 });


             }
  });

在一个更现代的方式,你现在可以使用Fetch API:

fetch("test.json")
  .then(response => response.json())
  .then(json => console.log(json));

所有现代浏览器都支持Fetch API。(Internet Explorer没有,但Edge有!)

或者使用async/await

async function printJSON() {
    const response = await fetch("test.json");
    const json = await response.json();
    console.log(json);
}

来源:

使用取回 正在执行的取回 我能用…吗? 如何使用Fetch与async/await