Load local JSON file into variable

JavascriptJqueryJson

Javascript Problem Overview


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: <https://stackoverflow.com/questions/2177548/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?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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

Solution 3 - Javascript

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

Solution 4 - Javascript

A solution without require or fs:

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

Solution 5 - Javascript

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

Solution 6 - Javascript

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.

Solution 7 - Javascript

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

Solution 8 - Javascript

To export a specific value from output.json (containing json shared on question) file to a variable say VAR :

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPogoMipsView Question on Stackoverflow
Solution 1 - JavascriptEhvinceView Answer on Stackoverflow
Solution 2 - JavascriptLittle RoysView Answer on Stackoverflow
Solution 3 - JavascriptKevin BView Answer on Stackoverflow
Solution 4 - JavascriptlafeberView Answer on Stackoverflow
Solution 5 - JavascriptArnaud M.View Answer on Stackoverflow
Solution 6 - JavascriptAaron DigullaView Answer on Stackoverflow
Solution 7 - JavascriptAnk_247shbmView Answer on Stackoverflow
Solution 8 - JavascriptKailashView Answer on Stackoverflow