162

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?

Skylar
  • 928
  • 5
  • 18
PogoMips
  • 3,497
  • 8
  • 27
  • 34
  • 1
    Your file url is `/content.json` which means that file is on root level of your web app. Change to `content.json` (without slash) to point it in the same directory where your script file is placed. Only in case if your script file is in root level directory it will works. – Samich Jan 23 '13 at 16:38
  • 1
    the file resides in WebContent\jit\content.json.. I tried 'url': "/WebContent/jit/content.json", but still the variable is null – PogoMips Jan 23 '13 at 16:39

10 Answers10

154

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))
  })
}
Ehvince
  • 17,274
  • 7
  • 58
  • 79
84

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,
     ...
  },
  ...
}
Little Roys
  • 5,383
  • 3
  • 30
  • 28
  • 7
    import isn't working in Chrome v72 - still `Uncaught SyntaxError: Unexpected token *` – 1000Gbps Feb 15 '19 at 23:01
  • 5
    When I use this, it seems `data` is a module but `data.default` is the object – Dustin Michels Apr 19 '19 at 17:38
  • 1
    I was trying to run this in console, but without a success. This does not work with node v12.4.0, with babel-node 6.26.0. I always get `SyntaxError: Unexpected token *` – mario199 Jun 15 '19 at 18:17
  • 4
    *for ES6/ES2015* you can import directly: It seems that I get a console error when doing `import * as data from './example.json'` due to a mime type error. – Fallenreaper Jul 16 '19 at 15:18
  • 2
    if I use `import * as data from './example.json';` then `data` is just module, but `data.default` is the object. But when I use `import data from './example.json';` then `data` is the object, which is more applicapable –  Oct 30 '19 at 13:02
  • If you are looking to use in a framework like Vue or React this works wonders THANK YOU – Nishank Sisodiya Aug 01 '20 at 09:12
  • Works perfectly. You only need to add `assert { type: 'json' }` after the path, so that javascript knows that it is a `json` file. So in your example: `import * as data from './example.json' assert { type: 'json' };` than you can acces the object using `data.default` – Mqx Apr 03 '23 at 05:45
46

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

Skylar
  • 928
  • 5
  • 18
Kevin B
  • 94,570
  • 16
  • 163
  • 180
  • 2
    I can't believe that fixed it.. why would it work directly embedded in the .js file without double quotes, but not in the .json file? That does not make any sense... – PogoMips Jan 23 '13 at 16:52
  • 20
    @user1695165 - json and a javascript object are two different things, they just look the same. – adeneo Jan 23 '13 at 16:53
  • 2
    @Kevin B "...unless the value is numeric [or boolean]." – Jacob Beauchamp May 19 '17 at 20:34
  • 2
    Just a tip: you can use a json validator like https://jsonlint.com/ in order to check your json data before using it. – Marco Panichi Nov 07 '17 at 07:29
12

A solution without require or fs:

var json = []
fetch('./content.json').then(response => json = response.json())
lafeber
  • 2,683
  • 1
  • 27
  • 29
6

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());
Arnaud M.
  • 139
  • 1
  • 6
6

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 and safari supported.

Read more at: v8 import assertions post

Anil kumar
  • 1,216
  • 4
  • 12
4

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.

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
3

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
Ank_247shbm
  • 512
  • 7
  • 17
  • 4
    This is an answer to a question that isn't the one asked here. – Kevin B Jun 10 '20 at 20:27
  • That's great, however, this question is about a user trying to copy an object literal into a .json file that they then load in with ajax, only, their object literal was in a format that wasn't valid for JSON. While installing react and importing this with require would certainly work in some cases, it doesn't really help *this* case. – Kevin B Jun 10 '20 at 20:36
  • As a note: posting comments linking to this answer on all other answers can be considered excessive self-promotion, and attempting to edit answers is vandalism. Your comments have been removed, and please don't make edits like this again. – Brad Larson Jun 11 '20 at 20:27
1

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)
Kailash
  • 219
  • 2
  • 4
1

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);
Kumawat Lalit
  • 410
  • 4
  • 8