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

有人有办法吗?


当前回答

从头开始添加到JSON文件中

var object1 = [

在最后

]

保存它

然后用纯js加载它

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

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

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

其他回答

你可以把json放在javascript文件中。这可以使用jQuery的getScript()函数在本地加载(甚至在Chrome中)。

图- 01. - js文件:

var json = '{"layers":6, "worldWidth":500, "worldHeight":400}'

main.js

$.getScript('map-01.js')
    .done(function (script, textStatus) {
        var map = JSON.parse(json); //json is declared in the js file
        console.log("world width: " + map.worldWidth);
        drawMap(map);
    })
    .fail(function (jqxhr, settings, exception) {
        console.log("error loading map: " + exception);
    });

输出:

world width: 500

注意,json变量是在js文件中声明和赋值的。

我也有同样的需求(测试我的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/

如何使用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

在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_str = 字符串.raw'[{“名称”: “Jeeva”}, {“名称”: “Kumar”}]'; obj = JSON.parse(json_str); console.log(obj[0][“name”]);

我为我的cordova应用程序这样做,就像我为JSON创建了一个新的javascript文件,并将JSON数据粘贴到String中。然后使用JSON.parse解析它