我试图加载一个本地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_str = 字符串.raw'[{“名称”: “Jeeva”}, {“名称”: “Kumar”}]'; obj = JSON.parse(json_str); console.log(obj[0][“name”]);

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

其他回答

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


             }
  });

如果你在你的本地机器上安装了Python(或者你不介意安装一个),这里有一个浏览器独立的解决方案,我使用的本地JSON文件访问问题:

通过创建一个将数据作为JavaScript对象返回的函数,将JSON文件转换为JavaScript文件。然后,您可以使用<script>标记加载它,并调用该函数以获得所需的数据。

下面是Python代码

import json


def json2js(jsonfilepath, functionname='getData'):
    """function converting json file to javascript file: json_data -> json_data.js
    :param jsonfilepath: path to json file
    :param functionname: name of javascript function which will return the data
    :return None
    """
    # load json data
    with open(jsonfilepath,'r') as jsonfile:
        data = json.load(jsonfile)
    # write transformed javascript file
    with open(jsonfilepath+'.js', 'w') as jsfile:
        jsfile.write('function '+functionname+'(){return ')
        jsfile.write(json.dumps(data))
        jsfile.write(';}')

if __name__ == '__main__':
    from sys import argv
    l = len(argv)
    if l == 2:
        json2js(argv[1])
    elif l == 3:
        json2js(argv[1], argv[2])
    else:
        raise ValueError('Usage: python pathTo/json2js.py jsonfilepath [jsfunctionname]')

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

json_str = 字符串.raw'[{“名称”: “Jeeva”}, {“名称”: “Kumar”}]'; obj = JSON.parse(json_str); console.log(obj[0][“name”]);

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

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