This will do it: var json = (function () { var json = null; $. ajax({ 'async': false, 'global': false, 'url': my_url, 'dataType': "json", 'success': function (data) { json = data; } }); return json; })(); The main issue being that $.
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 }
.
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');
fs.readFile('./content.json', (err, data) => {
if (err)
console.log(err);
else {
var json = JSON.parse(data);
//your code using json object
}
})
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())
There are two possible problems:
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]);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With