加载本地 JSON 文件

发布于 2024-12-04 02:42:24 字数 505 浏览 7 评论 0 原文

我正在尝试加载本地 JSON 文件,但它不起作用。这是我的 JavaScript 代码(使用 jQuery):

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

test.json 文件:

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

没有显示任何内容,Firebug 告诉我 data 未定义。在 Firebug 中,我可以看到 json.responseText ,它是好的且有效的,但是当我复制该行时很奇怪:

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

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

有人有解决办法吗?

I'm trying to load a local JSON file but it won't work. Here is my JavaScript code (using jQuery):

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

The test.json file:

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

Nothing is displayed and Firebug tells me that data is undefined. In Firebug I can see json.responseText and it is good and valid, but it's strange when I copy the line:

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

in Firebug's console, it works and I can access data.

Does anyone have a solution?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(26

苍白女子 2024-12-11 02:42:25

$.getJSON 仅在 Chrome 105.0.5195.125 中使用 await 对我有用,它适用于 modulescript type

<script type="module">
    const myObject = await $.getJSON('./myObject.json');
    console.log('myObject: ' + myObject);
</script>

如果没有 await,我会看到:

Uncaught TypeError: myObject is not iterable

解析 myObject 时。

没有 type="module" 我看到:

Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules

$.getJSON only worked for me in Chrome 105.0.5195.125 using await, which works a script type of module.

<script type="module">
    const myObject = await $.getJSON('./myObject.json');
    console.log('myObject: ' + myObject);
</script>

Without await, I see:

Uncaught TypeError: myObject is not iterable

when resolving myObject.

Without type="module" I see:

Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules
他夏了夏天 2024-12-11 02:42:25

我还没有找到任何使用 Google 的 Closure 库的解决方案。因此,为了完成未来访问者的列表,以下是使用 Closure 库从本地文件加载 JSON 的方法:

goog.net.XhrIo.send('../appData.json', function(evt) {
  var xhr = evt.target;
  var obj = xhr.getResponseJson(); //JSON parsed as Javascript object
  console.log(obj);
});

I haven't found any solution using Google's Closure library. So just to complete the list for future vistors, here's how you load a JSON from local file with Closure library:

goog.net.XhrIo.send('../appData.json', function(evt) {
  var xhr = evt.target;
  var obj = xhr.getResponseJson(); //JSON parsed as Javascript object
  console.log(obj);
});
旧梦荧光笔 2024-12-11 02:42:25
json_str = String.raw`[{"name": "Jeeva"}, {"name": "Kumar"}]`;
obj = JSON.parse(json_str);

console.log(obj[0]["name"]);

我为我的 cordova 应用程序执行了此操作,就像我为 JSON 创建了一个新的 javascript 文件并将 JSON 数据粘贴到 String.raw 中,然后使用 JSON.parse 解析它

json_str = String.raw`[{"name": "Jeeva"}, {"name": "Kumar"}]`;
obj = JSON.parse(json_str);

console.log(obj[0]["name"]);

I did this for my cordova app, like I created a new javascript file for the JSON and pasted the JSON data into String.raw then parse it with JSON.parse

从来不烧饼 2024-12-11 02:42:25
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");

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

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");

What I did was, first of all, from network tab, record the network traffic for the service, and from response body, copy and save the json object in a local file. Then call the function with the local file name, you should be able to see the json object in jsonOutout above.

完美的未来在梦里 2024-12-11 02:42:25

对我有用的是:

输入:

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, '&').replace(/</g, '<').replace(/>/g, '>');
    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>

What worked for me is the following:

Input:

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

Javascript Code:

<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, '&').replace(/</g, '<').replace(/>/g, '>');
    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>
肤浅与狂妄 2024-12-11 02:42:25

最简单的方法:将 json 文件另存为 *.js 并作为脚本包含到 html 模板中。

像这样的 js 文件:

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

这样包含:

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

包含后,您可以在全局范围内调用 fileJsonData

simplest way: save json file as *.js and include to html template as script.

js file like this:

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

include like this:

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

After include you can call to fileJsonData in global scope.

冷夜 2024-12-11 02:42:25

如果您的本地计算机上安装了 Python(或者您不介意安装 Python),那么我使用以下一种独立于浏览器的解决方法来解决本地 JSON 文件访问问题:

通过创建一个返回的函数,将 JSON 文件转换为 JavaScript作为 JavaScript 对象的数据。然后你可以使用

这里是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]')

If you have Python installed on your local machine (or you don't mind install one), here is a browser-independent workaround for local JSON file access problem that I use:

Transform the JSON file into a JavaScript by creating a function that returns the data as JavaScript object. Then you can load it with <script> tag and call the function to get the data you want.

Here comes the Python code

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]')
丶视觉 2024-12-11 02:42:24

$.getJSON 是异步的,所以你应该这样做:

$.getJSON("test.json", function(json) {
    console.log(json); // this will show the info it in firebug console
});

$.getJSON is asynchronous so you should do:

$.getJSON("test.json", function(json) {
    console.log(json); // this will show the info it in firebug console
});
錯遇了你 2024-12-11 02:42:24

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

I had the same need (to test my angularjs app), and the only way I found is to use require.js:

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

note: the file is loaded once, further calls will use the cache.

More on reading files with nodejs: http://docs.nodejitsu.com/articles/file-system/how-to-read-files-in-nodejs

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

邮友 2024-12-11 02:42:24

现在,您可以以更现代的方式使用 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);
}

源:

In a more modern way, you can now use the Fetch API:

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

All modern browsers support Fetch API. (Internet Explorer doesn't, but Edge does!)

or with async/await

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

source:

伴我心暖 2024-12-11 02:42:24

如果您想让用户选择本地 json 文件(文件系统上的任何位置),则以下解决方案有效。

它使用 FileReader 和 JSON.parser (并且没有 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/教程/文件/dndfiles/

If you want to let the user select the local json file (anywhere on the filesystem), then the following solution works.

It uses FileReader and JSON.parser (and no 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>

Here is a good intro on FileReader: http://www.html5rocks.com/en/tutorials/file/dndfiles/

萌能量女王 2024-12-11 02:42:24

如果您正在寻找简单的东西,只需将数据加载到 HTML 的 head 中即可:

data.js

var DATA = {"a" : "b", "c" : "d"};

index.html

<head>
   <script src="data.js" ></script>
   <script src="main.js" ></script>
</head>

main.js

(function(){
   console.log(DATA); // {"a" : "b", "c" : "d"}
})();

但是,如果您的数据大于堆大小,请尝试另一个浏览器。要检查大小,请执行以下操作:

window.performance.memory.jsHeapSizeLimit / 1024 / 1024 / 1024 + " GBs"
// "4.046875 GBs"

更新 ES6:

您可以使用 main.js 中加载数据,而不是使用

import data from './data.json' assert {type: 'json'};

If you're looking for something simple, just load the data in the head of your HTML:

data.js

var DATA = {"a" : "b", "c" : "d"};

index.html

<head>
   <script src="data.js" ></script>
   <script src="main.js" ></script>
</head>

main.js

(function(){
   console.log(DATA); // {"a" : "b", "c" : "d"}
})();

However, if your data is larger than your heap size, try another browser. To check the size do:

window.performance.memory.jsHeapSizeLimit / 1024 / 1024 / 1024 + " GBs"
// "4.046875 GBs"

Update ES6:

Instead of using the <script> tag to load your data, you can load it directly inside your main.js using import assert

import data from './data.json' assert {type: 'json'};
拿命拼未来 2024-12-11 02:42:24

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

how to using XMLHttpRequest to load the local json file

ES5 version

// 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 version

// 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>

online demo

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

少年亿悲伤 2024-12-11 02:42:24

添加到您的 JSON 文件中

var object1 = [

从头到尾

]

保存它

然后使用纯 js 加载它

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

现在您可以将它用作 object1 - 它已经加载了!

在 Chrome 中完美运行,无需任何额外的库

Add to your JSON file from the beginning

var object1 = [

and at the end

]

Save it

Then load it with pure js as

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

And now you can use it as object1 - its already loaded!

Works perfectly in Chrome and without any additional libraries

夜深人未静 2024-12-11 02:42:24

我不敢相信这个问题已经被回答了多少次而没有理解和/或解决原始海报的实际代码的问题。也就是说,我自己是个初学者(只花了 2 个月的时间编码)。我的代码确实可以完美运行,但请随时提出对其进行任何更改的建议。 这是解决方案:

//include the   'async':false   parameter or the object data won't get captured when loading
var json = $.getJSON({'url': "http://spoonertuner.com/projects/test/test.json", 'async': false});  

//The next line of code will filter out all the unwanted data from the object.
json = JSON.parse(json.responseText); 

//You can now access the json variable's object data like this json.a and json.c
document.write(json.a);
console.log(json);

这是编写我上面提供的相同代码的更简短的方法:

var json = JSON.parse($.getJSON({'url': "http://spoonertuner.com/projects/test/test.json", 'async': false}).responseText);

您还可以使用 $.ajax 而不是 $.getJSON 来以完全相同的方式编写代码:

var json = JSON.parse($.ajax({'url': "http://spoonertuner.com/projects/test/test.json", 'async': false}).responseText); 

最后,最后一种方法是将 $.ajax 包装在函数中。我不能将此归功于我,但我确实对其进行了一些修改。我测试了它,它可以工作并产生与上面的代码相同的结果。我在这里找到了这个解决方案 --> 将 json 加载到变量中

var json = function () {
    var jsonTemp = null;
    $.ajax({
        'async': false,
        'url': "http://spoonertuner.com/projects/test/test.json",
        'success': function (data) {
            jsonTemp = data;
        }
    });
    return jsonTemp;
}(); 

document.write(json.a);
console.log(json);

test.json 文件您在上面的代码中看到托管在我的服务器上,并包含他(原始发布者)发布的相同 json 数据对象。

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

I can't believe how many times this question has been answered without understanding and/or addressing the problem with the Original Poster's actual code. That said, I'm a beginner myself (only 2 months of coding). My code does work perfectly, but feel free to suggest any changes to it. Here's the solution:

//include the   'async':false   parameter or the object data won't get captured when loading
var json = $.getJSON({'url': "http://spoonertuner.com/projects/test/test.json", 'async': false});  

//The next line of code will filter out all the unwanted data from the object.
json = JSON.parse(json.responseText); 

//You can now access the json variable's object data like this json.a and json.c
document.write(json.a);
console.log(json);

Here's a shorter way of writing the same code I provided above:

var json = JSON.parse($.getJSON({'url': "http://spoonertuner.com/projects/test/test.json", 'async': false}).responseText);

You can also use $.ajax instead of $.getJSON to write the code exactly the same way:

var json = JSON.parse($.ajax({'url': "http://spoonertuner.com/projects/test/test.json", 'async': false}).responseText); 

Finally, the last way to do this is to wrap $.ajax in a function. I can't take credit for this one, but I did modify it a bit. I tested it and it works and produces the same results as my code above. I found this solution here --> load json into variable

var json = function () {
    var jsonTemp = null;
    $.ajax({
        'async': false,
        'url': "http://spoonertuner.com/projects/test/test.json",
        'success': function (data) {
            jsonTemp = data;
        }
    });
    return jsonTemp;
}(); 

document.write(json.a);
console.log(json);

The test.json file you see in my code above is hosted on my server and contains the same json data object that he (the original poster) had posted.

{
    "a" : "b",
    "c" : "d"
}
樱花落人离去 2024-12-11 02:42:24

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

例如:import test from './test.json'

webpack 2<使用 json-loader 作为 .json 文件的默认值。

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

对于 TypeScript

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 /迁移/#automatic-loader-module-name-extension-removed

I'm surprised import from es6 has not been mentioned (use with small files)

Ex: import test from './test.json'

webpack 2< uses the json-loader as default for .json files.

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

For TypeScript:

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

TS2307 (TS) Cannot find module 'json-loader!./suburbs.json'

To get it working I had to declare the module first. I hope this will save a few hours for someone.

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

...

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

If I tried to omit loader from json-loader I got the following error from webpack:

BREAKING CHANGE: It's no longer allowed to omit the '-loader' suffix
when using loaders.
You need to specify 'json-loader' instead of 'json',
see https://webpack.js.org/guides/migrating/#automatic-loader-module-name-extension-removed

新雨望断虹 2024-12-11 02:42:24

最近 D3js 能够处理本地 json 文件。

这就是问题所在
https://github.com/mbostock/d3/issues/673

这是补丁为了让 D3 能够处理本地 json 文件。
https://github.com/mbostock/d3/pull/632

Recently D3js is able to handle local json file.

This is the issue
https://github.com/mbostock/d3/issues/673

This is the patch inorder for D3 to work with local json files.
https://github.com/mbostock/d3/pull/632

許願樹丅啲祈禱 2024-12-11 02:42:24

在尝试(不成功)加载本地 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)
}

并且像这样使用

load_json("test2.html.js")

......这是 ......

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

Found this thread when trying (unsuccessfully) to load a local json file. This solution worked for me...

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 is used like this...

load_json("test2.html.js")

...and this is the <head>...

<head>
  <script type="text/javascript" src="test.html.js" class="json"></script>
</head>
爱要勇敢去追 2024-12-11 02:42:24

我所做的就是稍微编辑一下 JSON 文件。

myfile.json =>; myfile.js

在 JSON 文件中,(使其成为 JS 变量)

{name: "Whatever"} => var x = {name: "Whatever"}

最后,

export default x;

然后,

import JsonObj from './myfile.js';代码>

What I did was editing the JSON file little bit.

myfile.json => myfile.js

In the JSON file, (make it a JS variable)

{name: "Whatever"} => var x = {name: "Whatever"}

At the end,

export default x;

Then,

import JsonObj from './myfile.js';

不气馁 2024-12-11 02:42:24

在 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

In TypeScript you can use import to load local JSON files. For example loading a font.json:

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

This requires a tsconfig flag --resolveJsonModule:

// tsconfig.json

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

For more information see the release notes of typescript: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-9.html

左耳近心 2024-12-11 02:42:24

我喜欢使用的一种方法是用对象文字填充/包装 json,然后使用 .jsonp 文件扩展名保存文件。此方法还会保留原始 json 文件 (test.json) 不变,因为您将使用新的 jsonp 文件 (test.jsonp)。包装器上的名称可以是任何名称,但它确实需要与用于处理 jsonp 的回调函数名称相同。我将使用您发布的 test.json 作为示例来显示“test.jsonp”文件的 jsonp 包装添加。

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 验证器上检查它。

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"});

Next, create a reusable variable with global scope in your script to hold the returned JSON. This will make the returned JSON data available to all other functions in your script instead of just the callback function.

var myJSON;

Next comes a simple function to retrieve your json by script injection. Note that we can not use jQuery here to append the script to the document head, as IE does not support the jQuery .append method. The jQuery method commented out in the code below will work on other browsers that do support the .append method. It is included as a reference to show the difference.

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)
}

Next is a short and simple callback function (with the same name as the jsonp wrapper) to get the json results data into the global variable.

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

The json data can now be accessed by any functions of the script using dot notation. As an example:

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

This method may be a bit different from what you are used to seeing, but has many advantages. First, the same jsonp file can be loaded locally or from a server using the same functions. As a bonus, jsonp is already in a cross-domain friendly format and can also be easily used with REST type API's.

Granted, there are no error handling functions, but why would you need one? If you are unable to get the json data using this method, then you can pretty much bet you have some problems within the json itself, and I would check it on a good JSON validator.

瀟灑尐姊 2024-12-11 02:42:24

在 Angular(或任何其他框架)中,您可以使用 http get 加载
我这样使用它:

this.http.get(<path_to_your_json_file))
 .success((data) => console.log(data));

希望这有帮助。

In angular (or any other framework), you can load using http get
I use it something like this:

this.http.get(<path_to_your_json_file))
 .success((data) => console.log(data));

Hope this helps.

小姐丶请自重 2024-12-11 02:42:24

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

map-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 文件中声明并赋值的。

You can put your json in a javascript file. This can be loaded locally (even in Chrome) using jQuery's getScript() function.

map-01.js file:

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);
    });

output:

world width: 500

Notice that the json variable is declared and assigned in the js file.

习惯成性 2024-12-11 02:42:24
$.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_);
                      }
                 });


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


             }
  });
南冥有猫 2024-12-11 02:42:24

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

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

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

If you are using a local array for JSON - as you showed in your example in the question (test.json) then you can is the parseJSON() method of JQuery ->

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

getJSON() is used for getting JSON from a remote site - it will not work locally (unless you are using a local HTTP Server)

找个人就嫁了吧 2024-12-11 02:42:24

我如何使用简单的 JavaScript 将数据从 json 文件加载到 JavaScript 变量中:

let mydata;
fetch('datafile.json')
    .then(response => response.json()) 
    .then(jsonResponse => mydata = jsonResponse)

在此发布,因为我没有找到我正在寻找的这种“解决方案”。

注意:我使用的是通过通常的“

How I was able to load the data from a json file in to a JavaScript variable using simple JavaScript:

let mydata;
fetch('datafile.json')
    .then(response => response.json()) 
    .then(jsonResponse => mydata = jsonResponse)

Posting here as I didn't find this kind of "solution" I was looking for.

Note: I am using a local server run via the usual "python -m http.server" command.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文