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

有人有办法吗?


当前回答

对我有效的方法如下:

输入:

http://ip_address//some_folder_name//render_output.html?relative/path/to/json/fie.json

Javascript代码:

<html>
<head>

<style>
pre {}
.string { color: green; }
.number { color: darkorange; }
.boolean { color: blue; }
.null { color: magenta; }
.key { color: red; }
</style>

<script>
function output(inp) {
    document.body.appendChild(document.createElement('pre')).innerHTML = inp;
}

function gethtmlcontents(){
    path = window.location.search.substr(1)
    var rawFile = new XMLHttpRequest();
    var my_file = rawFile.open("GET", path, true)  // Synchronous File Read
    //alert('Starting to read text')
    rawFile.onreadystatechange = function ()
    {
        //alert("I am here");
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;
                //alert(allText)
                var json_format = JSON.stringify(JSON.parse(allText), null, 8)
                //output(json_format)
                output(syntaxHighlight(json_format));
            }
        }
    }
    rawFile.send(null);
}

function syntaxHighlight(json) {
    json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
        var cls = 'number';
        if (/^"/.test(match)) {
            if (/:$/.test(match)) {
                cls = 'key';
            } else {
                cls = 'string';
            }
        } else if (/true|false/.test(match)) {
            cls = 'boolean';
        } else if (/null/.test(match)) {
            cls = 'null';
        }
        return '<span class="' + cls + '">' + match + '</span>';
    });
}

gethtmlcontents();
</script>
</head>
<body>
</body>
</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放在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文件中声明和赋值的。

如果您想让用户选择本地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/

An approach I like to use is to pad/wrap the json with an object literal, and then save the file with a .jsonp file extension. This method also leaves your original json file (test.json) unaltered, as you will be working with the new jsonp file (test.jsonp) instead. The name on the wrapper can be anything, but it does need to be the same name as the callback function you use to process the jsonp. I'll use your test.json posted as an example to show the jsonp wrapper addition for the 'test.jsonp' file.

json_callback({"a" : "b", "c" : "d"});

接下来,在脚本中创建一个具有全局作用域的可重用变量,以保存返回的JSON。这将使返回的JSON数据可用于脚本中的所有其他函数,而不仅仅是回调函数。

var myJSON;

接下来是一个通过脚本注入检索json的简单函数。注意,我们不能在这里使用jQuery将脚本附加到文档头部,因为IE不支持jQuery .append方法。下面代码中注释掉的jQuery方法可以在其他支持.append方法的浏览器上运行。这是作为一个参考,以显示差异。

function getLocalJSON(json_url){
    var json_script  = document.createElement('script');
    json_script.type = 'text/javascript';
    json_script.src  = json_url;
    json_script.id   = 'json_script';
    document.getElementsByTagName('head')[0].appendChild(json_script);
    // $('head')[0].append(json_script); DOES NOT WORK in IE (.append method not supported)
}

接下来是一个简短的回调函数(与jsonp包装器同名),用于将json结果数据获取到全局变量中。

function json_callback(response){
    myJSON = response;            // Clone response JSON to myJSON object
    $('#json_script').remove();   // Remove json_script from the document
}

json数据现在可以被脚本的任何函数使用点表示法访问。举个例子:

console.log(myJSON.a); // Outputs 'b' to console
console.log(myJSON.c); // Outputs 'd' to console

这种方法可能与你习惯看到的有点不同,但有很多优点。首先,可以使用相同的函数在本地或从服务器加载相同的jsonp文件。作为奖励,jsonp已经是跨域友好的格式,也可以很容易地与REST类型API一起使用。

当然,没有错误处理函数,但为什么需要呢?如果您无法使用此方法获得json数据,那么您几乎可以打赌json本身存在一些问题,我会在一个好的json验证器上检查它。

最简单的方法:保存json文件为*.js,并包括到HTML模板作为脚本。

Js文件是这样的:

let fileJsonData = {
  someField: someValue,
  ...
}

包括如下内容:

...
<script src="./js/jsonData.js"></script>
...

include之后,你可以在全局范围内调用fileJsonData。