简体   繁体   中英

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. It's probably just a minor error but I can't find it.

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.json file and tried to load that into a local JavaScript variable as explained here: load json into variable .

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 . The content.json file resides in the same directory as the.js file that calls it.

What did I miss?

My solution, as answered here , is to use:

    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:

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:

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

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

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

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

If you pasted your object into content.json directly, it is invalid 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.

{
  "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. When the file has been loaded, the callback function will set json to 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.

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

You can load it using 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:

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

inorder to import to .js file like ~/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:

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

for free JSON files to work with go to https://jsonplaceholder.typicode.com/

and to import your JSON files try this

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.

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

Browser support: till september 2022, only chromium based browsers supported.

Read more at: v8 import assertions post

Import a JSON file with ES6:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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