[javascript] 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?

This question is related to javascript jquery json

The answer is


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

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

A solution without require or fs:

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

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,
     ...
  },
  ...
}

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.


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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?