简体   繁体   English

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

[英]Load local JSON file into variable

I'm trying to load a.json file into a variable in javascript, but I can't get it to work.我试图将 a.json 文件加载到 javascript 中的一个变量中,但我无法让它工作。 It's probably just a minor error but I can't find it.这可能只是一个小错误,但我找不到它。

Everything works just fine when I use static data like this:当我像这样使用 static 数据时,一切正常:

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.json file 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 json is null .我用 Chrome 调试器运行它,它总是告诉我变量json的值是null The content.json file resides in the same directory as the.js file that calls it. content.json文件与调用它的 .js 文件位于同一目录中。

What did I miss?我错过了什么?

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.该文件只加载一次,进一步的请求使用缓存。

edit To avoid caching, here's the helper function from this blogpost given in the comments, using the fs module:编辑为了避免缓存,这里是评论中给出的这篇博文中的辅助函数,使用fs模块:

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

For ES6/ES2015 you can import directly 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 -- resolveJsonModule compilerOptions in tsconfig.json从 Typescript 2.9+ 开始,您可以在tsconfig.json添加--resolveJsonModule compilerOptions

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

If you pasted your object into content.json directly, it is invalid JSON.如果直接将对象粘贴到content.json ,则它是无效的 JSON。 JSON keys and values must be wrapped in double quotes ( " not ' ) unless the value is numeric, boolean, null , or composite (array or object). JSON cannot contain functions or undefined values. Below is your object as valid JSON. JSON 键值必须用双引号( "而不是' )括起来,除非值是数字、布尔值、 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 } .你还有一个额外的}

There are two possible problems:有两个可能的问题:

  1. AJAX is asynchronous, so json will be undefined when you return from the outer function. AJAX 是异步的,因此当您从外部函数返回时, json将是未定义的。 When the file has been loaded, the callback function will set json to some value but at that time, nobody cares anymore.当文件被加载后,回调函数会将json设置为某个值,但到那时,没有人会在意了。

    I see that you tried to fix this with 'async': false .我看到你试图用'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.使用您用来在 HTML 文档中加载脚本的相同路径。 So if your script is js/script.js , use js/content.json因此,如果您的脚本是js/script.js ,请使用js/content.json

    Some browsers can show you which URLs they tried to access and how that went (success/error codes, HTML headers, etc).某些浏览器可以向您显示他们尝试访问的 URL 以及访问方式(成功/错误代码、HTML 标头等)。 Check your browser's development tools to see what happens.检查浏览器的开发工具,看看会发生什么。

The built-in node.js module fs will 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');加载它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());

For the given json format as in file ~/my-app/src/db/abc.json:对于文件 ~/my-app/src/db/abc.json 中给定的 json 格式:

  [
      {
        "name":"Ankit",
        "id":1
      },
      {
        "name":"Aditi",
        "id":2
      },
      {
        "name":"Avani",
        "id":3
      }
  ]

inorder to import to .js file like ~/my-app/src/app.js:为了导入到 .js 文件,如 ~/my-app/src/app.js:

 const json = require("./db/abc.json");

 class Arena extends React.Component{
   render(){
     return(
       json.map((user)=>
        {
          return(
            <div>{user.name}</div>
          )
        }
       )
      }
    );
   }
 }

 export default Arena;

Output:输出:

Ankit Aditi Avani

A solution without require or fs:没有 require 或 fs 的解决方案:

var json = []
fetch('./content.json').then(response => json = response.json())

for free JSON files to work with go to https://jsonplaceholder.typicode.com/免费的 JSON 个文件可以与 go 一起使用到https://jsonplaceholder.typicode.com/

and to import your JSON files try this并导入您的 JSON 文件试试这个

const dataframe1=require('./users.json');
console.log(dataframe1);

要将 output.json(包含问题共享的 json)文件中的特定值导出到变量,请说 VAR:

export VAR=$(jq -r '.children.id' output.json)

Answer from future.来自未来的答案。
In 2022, we have import assertions api for import json file in js file.在 2022 年,我们在 js 文件中有导入断言 api 用于导入 json 文件。

import myjson from "./myjson.json" assert { type: "json" };
console.log(myjson);

Browser support: till september 2022, only chromium based browsers supported.浏览器支持:直到 2022 年 9 月,仅支持基于 chromium 的浏览器。

Read more at: v8 import assertions post阅读更多内容: v8 导入断言帖子

Import a JSON file with ES6: 使用ES6导入JSON文件:

import myJson from '/path/to/filename.json'
myJsonString = JSON.stringify(myJson)

If the file is in the same directory, you can use 如果文件在同一目录中,则可以使用

import myJson from './filename.json

Before ES6 在ES6之前

var json = require('./filename.json');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM