Load the local JSON file into a variable

I am trying to load a .json file into a variable in javascript, but I cannot get it to work. This is probably a small mistake, but I can not find it.

Everything works fine when I use static data as follows:

var json = { id: "whatever", name: "start", children: [{ "id":"0.9685","name":" contents:queue"},{ "id":"0.79281","name":" contents:mqq_error"}}] } 

So I put everything in {} in the content.json file and tried to load it into a local javascript variable as described here: load json into a 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 a chrome debugger, and it always tells me that the value of the json variable is null. Content.json is in the same directory as the .js file that calls it.

What did I miss?

+81
json javascript jquery
Jan 23 '13 at 16:34
source share
6 answers

If you pasted your object directly into content.json, this is invalid json. JSON keys AND values ​​must be enclosed in double quotes (not single!), Unless that value is numerical or logical. Below will be 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 } )

+33
Jan 23 '13 at 16:43
source share

My solution, as answered here , is to use:

  var json = require('./data.json'); //with path 

The file is downloaded only once, further requests use the cache.

edit To avoid caching, here is a helper function from this post 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)) }) } 
+101
Aug 05 '13 at 14:24
source share

For ES6 / ES2015, you can import directly, for example:

 // example.json { "name": "testing" } // ES6/ES2015 // app.js import * as data from './example.json'; const {name} = data; console.log(name); // output 'testing' 

If you are using Typescript, you can declare a json module as follows:

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

Starting with Typescript 2. 9+ you can add - resolJsonModule compilerOptions in tsconfig.json

 { "compilerOptions": { "target": "es5", ... "resolveJsonModule": true, ... }, ... } 
+29
May 26 '18 at 6:38
source share

Two problems are possible:

  • AJAX is asynchronous, so json will be undefined when you return from an external function. When the file has been downloaded, the callback function will set json to some value, but no one else cares at that time.

    I see that you tried to fix this with 'async': false . To check if this works, add this line to your code and check your browser console:

     console.log(['json', json]); 
  • The path may be wrong. Use the same path used to load the script in the HTML document. Therefore, if your script is js/script.js , use js/content.json

    Some browsers may show you which URLs they tried to access and how it happened (success / error codes, HTML headers, etc.). Check your browser development tools to see what happens.

+4
Jan 23 '13 at 16:38
source share

The node.js fs built-in module will do this 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()); 
+2
Nov 27. '18 at
source share

Import the 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 

Up to ES6

 var json = require('./filename.json'); 
-one
Aug 05 '19 at 4:30
source share



All Articles