我试图加载一个本地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的控制台中,它可以工作,我可以访问数据。

有人有办法吗?


当前回答

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


             }
  });

其他回答

在尝试(不成功)加载本地json文件时发现此线程。这个方法对我很有效。

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的用法是这样的…

load_json("test2.html.js")

...这是<head>…

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

如何使用XMLHttpRequest加载本地json文件

ES5版本

// required use of an anonymous callback, // as .open() will NOT return a value but simply returns undefined in asynchronous mode! function loadJSON(callback) { var xObj = new XMLHttpRequest(); xObj.overrideMimeType("application/json"); xObj.open('GET', './data.json', true); // 1. replace './data.json' with the local path of your file xObj.onreadystatechange = function() { if (xObj.readyState === 4 && xObj.status === 200) { // 2. call your callback function callback(xObj.responseText); } }; xObj.send(null); } function init() { loadJSON(function(response) { // 3. parse JSON string into JSON Object console.log('response =', response); var json = JSON.parse(response); console.log('your local JSON =', JSON.stringify(json, null, 4)); // 4. render to your page const app = document.querySelector('#app'); app.innerHTML = '<pre>' + JSON.stringify(json, null, 4) + '</pre>'; }); } init(); <section id="app"> loading... </section>

ES6版本

// required use of an anonymous callback, // as .open() will NOT return a value but simply returns undefined in asynchronous mode! const loadJSON = (callback) => { const xObj = new XMLHttpRequest(); xObj.overrideMimeType("application/json"); // 1. replace './data.json' with the local path of your file xObj.open('GET', './data.json', true); xObj.onreadystatechange = () => { if (xObj.readyState === 4 && xObj.status === 200) { // 2. call your callback function callback(xObj.responseText); } }; xObj.send(null); } const init = () => { loadJSON((response) => { // 3. parse JSON string into JSON Object console.log('response =', response); const json = JSON.parse(response); console.log('your local JSON =', JSON.stringify(json, null, 4)); // 4. render to your page const app = document.querySelector('#app'); app.innerHTML = `<pre>${JSON.stringify(json, null, 4)}</pre>`; }); } init(); <section id="app"> loading... </section>

在线演示

https://cdn.xgqfrms.xyz/ajax/XMLHttpRequest/index.html

我也有同样的需求(测试我的angularjs应用程序),我发现唯一的方法是使用require.js:

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

注意:文件只加载一次,以后的调用将使用缓存。

关于使用nodejs读取文件的更多信息:http://docs.nodejitsu.com/articles/file-system/how-to-read-files-in-nodejs

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

在TypeScript中,你可以使用import来加载本地JSON文件。例如,加载一个font.json:

import * as fontJson from '../../public/fonts/font_name.json';

这需要tsconfig标志——resolveJsonModule:

// tsconfig.json

{
    "compilerOptions": {
        "module": "commonjs",
        "resolveJsonModule": true,
        "esModuleInterop": true
    }
}

有关更多信息,请参阅typescript的发布说明:https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-9.html

如果您正在使用JSON的本地数组-正如您在问题(test.json)中的示例中所示,那么您可以使用JQuery的parseJSON()方法->

var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );

getJSON()用于从远程站点获取JSON -它不会在本地工作(除非您使用本地HTTP服务器)