I'm trying to load a local JSON file but it won't work. Here is my JavaScript code (using jQuery:
var json = $.getJSON("test.json");
var data = eval("(" +json.responseText + ")");
document.write(data["a"]);
The test.json file:
{"a" : "b", "c" : "d"}
Nothing is displayed and Firebug tells me that data is undefined. In Firebug I can see json.responseText
and it is good and valid, but it's strange when I copy the line:
var data = eval("(" +json.responseText + ")");
in Firebug's console, it works and I can access data.
Anyone have a solution?
What worked for me is the following:
Input:
Javascript Code:
In a more modern way, you can now use the Fetch API:
All modern browsers support Fetch API. (Internet Explorer doesn't, but Edge does!)
source:
Using Fetch
Fetch in Action
Can I use...?
In angular (or any other framework), you can load using http get I use it something like this:
Hope this helps.
I did this for my cordova app, like I created a new javascript file for the JSON and pasted the JSON data into
String.raw
then parse it withJSON.parse
I'm surprised import from es6 has not been mentioned (use with small files)
Ex:
import test from './test.json'
webpack 2< uses the
json-loader
as default for.json
files.https://webpack.js.org/guides/migrating/#json-loader-is-not-required-anymore
For TypeScript:
To get it working I had to declare the module first. I hope this will save a few hours for someone.
If I tried to omit
loader
fromjson-loader
I got the following error fromwebpack
:Try is such way (but also please note that JavaScript don't have access to the client file system):