Javascript 将本地 JSON 文件加载到变量中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14484613/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 16:57:25  来源:igfitidea点击:

Load local JSON file into variable

javascriptjqueryjson

提问by PogoMips

I'm trying to load a .json file into a variable in javascript, but I can't get it to work. It's probably just a minor error but I can't find it.

我正在尝试将 .json 文件加载到 javascript 中的变量中,但我无法让它工作。这可能只是一个小错误,但我找不到它。

Everything works just fine when I use static data like this:

当我使用这样的静态数据时,一切正常:

var json = {
  id: "whatever",
  name: "start",
  children: [{
      "id": "0.9685",
      "name": " contents:queue"
    }, {
      "id": "0.79281",
      "name": " contents:mqq_error"
    }
  }]
}

I put everything that's in the {}in a content.jsonfile and tried to load that into a local JavaScript variable as explained here: load json into variable.

我将 中的所有内容都{}放在一个content.json文件中,并尝试将其加载到本地 JavaScript 变量中,如下所述:将json 加载到变量中

var json = (function() {
  var json = null;
  $.ajax({
    'async': false,
    'global': false,
    'url': "/content.json",
    'dataType': "json",
    'success': function(data) {
      json = data;
    }
  });
  return json;
})();

I ran it with the Chrome debugger and it always tells me that the value of the variable jsonis null. The content.jsonfile resides in the same directory as the .js file that calls it.

我用 Chrome 调试器运行它,它总是告诉我变量的值jsonnull. 该content.json文件与调用它的 .js 文件位于同一目录中。

What did I miss?

我错过了什么?

采纳答案by Kevin B

If you pasted your object into content.jsondirectly, it is invalid JSON. JSON keys andvalues must be wrapped in double quotes ("not ') unless the value is numeric, boolean, null, or composite (array or object). JSON cannot contain functions or undefinedvalues. Below is your object as valid JSON.

如果content.json直接将对象粘贴到其中,则它是无效的 JSON。JSON 键值必须用双引号("not ')括起来,除非值是数字、布尔值null、 或复合(数组或对象)。JSON 不能包含函数或undefined值。以下是您作为有效 JSON 的对象。

{
  "id": "whatever",
  "name": "start",
  "children": [
    {
      "id": "0.9685",
      "name": " contents:queue"
    },
    {
      "id": "0.79281",
      "name": " contents:mqq_error"
    }
  ]
}

You also had an extra }.

你还有一个额外的}.

回答by Ehvince

My solution, as answered here, is to use:

我的解决方案,如回答here,是使用:

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

The file is loaded only once, further requests use cache.

该文件只加载一次,进一步的请求使用缓存。

editTo avoid caching, here's the helper function from this blogpostgiven in the comments, using the fsmodule:

编辑为了避免缓存,是评论中给出的这篇博文中的辅助函数,使用fs模块:

var readJson = (path, cb) => {
  fs.readFile(require.resolve(path), (err, data) => {
    if (err)
      cb(err)
    else
      cb(null, JSON.parse(data))
  })
}

回答by Little Roys

For ES6/ES2015 you can importdirectly like:

对于 ES6/ES2015,您可以直接导入,如:

// example.json
{
    "name": "testing"
}


// ES6/ES2015
// app.js
import * as data from './example.json';
const {name} = data;
console.log(name); // output 'testing'

If you use Typescript, you may declare json module like:

如果你使用 Typescript,你可以像这样声明 json 模块:

// tying.d.ts
declare module "*.json" {
    const value: any;
    export default value;
}

Since Typescript 2.9+ you can add --resolveJsonModulecompilerOptions in tsconfig.json

从 Typescript 2.9+ 开始,您可以添加--resolveJsonModulecompilerOptionstsconfig.json

{
  "compilerOptions": {
    "target": "es5",
     ...
    "resolveJsonModule": true,
     ...
  },
  ...
}

回答by Arnaud M.

The built-in node.js module fswill do it either asynchronously or synchronously depending on your needs.

内置的node.js 模块 fs将根据您的需要异步或同步执行此操作。

You can load it using var fs = require('fs');

您可以使用加载它 var fs = require('fs');

Asynchronous

异步

fs.readFile('./content.json', (err, data) => {
    if (err)
      console.log(err);
    else {
      var json = JSON.parse(data);
    //your code using json object
    }
})

Synchronous

同步

var json = JSON.parse(fs.readFileSync('./content.json').toString());

回答by Aaron Digulla

There are two possible problems:

有两个可能的问题:

  1. AJAX is asynchronous, so jsonwill be undefined when you return from the outer function. When the file has been loaded, the callback function will set jsonto some value but at that time, nobody cares anymore.

    I see that you tried to fix this with 'async': false. To check whether this works, add this line to the code and check your browser's console:

    console.log(['json', json]);
    
  2. The path might be wrong. Use the same path that you used to load your script in the HTML document. So if your script is js/script.js, use js/content.json

    Some browsers can show you which URLs they tried to access and how that went (success/error codes, HTML headers, etc). Check your browser's development tools to see what happens.

  1. AJAX 是异步的,因此json当您从外部函数返回时将是未定义的。当文件被加载后,回调函数将设置json为某个值,但到那时,没有人会在意了。

    我看到你试图用'async': false. 要检查这是否有效,请将此行添加到代码中并检查浏览器的控制台:

    console.log(['json', json]);
    
  2. 路径可能不对。使用您用来在 HTML 文档中加载脚本的相同路径。因此,如果您的脚本是js/script.js,请使用js/content.json

    某些浏览器可以向您显示他们尝试访问的 URL 以及访问方式(成功/错误代码、HTML 标头等)。检查浏览器的开发工具,看看会发生什么。