Here's an example that doesn't require jQuery:
function loadJSON(path, success, error)
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
if (success)
success(JSON.parse(xhr.responseText));
} else {
if (error)
error(xhr);
}
}
};
xhr.open("GET", path, true);
xhr.send();
}
Call it as:
loadJSON('my-file.json',
function(data) { console.log(data); },
function(xhr) { console.error(xhr); }
);
Answer from Drew Noakes on Stack OverflowHere's an example that doesn't require jQuery:
function loadJSON(path, success, error)
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
if (success)
success(JSON.parse(xhr.responseText));
} else {
if (error)
error(xhr);
}
}
};
xhr.open("GET", path, true);
xhr.send();
}
Call it as:
loadJSON('my-file.json',
function(data) { console.log(data); },
function(xhr) { console.error(xhr); }
);
XHR can be used to open files, but then you're basically making it hard on yourself because jQuery makes this a lot easier for you. $.getJSON() makes this so easy to do. I'd rather want to call a single line than trying to get a whole code block working, but that's up to you...
Why i dont want to use jQuery is because the person i am working for doesn't want it because he is afraid of the speed of the script.
If he can't properly profile native VS jQuery, he shouldn't even be programming native code.
Being afraid means he doesn't know what he is doing. If you plan to go for performance, you actually need to know how to see how to make certain pieces of code faster. If you are only just thinking that jQuery is slow, then you are walking into the wrong roads...
Videos
Hello, so I'm developing a angularjs app, that needs to load local json files without making request, because this app is offline, doesn't have a web server running, so request will not work, any idea?
If you want it as simple as it gets, then I would prefix your json content with
var jsonData = {"UIGroup": {"Parent": null, "Type": "public"}}....
which turns your file into a valid js file and then load it with
<script src="fakeData.json.js"></script>
after that, jsonData will have the required content because of literal object notation.
There is no way that you can load a json file into your page otherwise without ajax/httprequest.
You need to get the JSON text into a string variable before you can parse it.
This is generally achieved using the XMLHttpRequest object.
<script src="fakeData.json"></script> will attempt to parse the JSON as JavaScript. This will either throw an error (as it does in your case) or create a data structure and then immediately discard it as it isn't assigned there.
I'm working on a platformer game in HTML, and have the level data stored in a JSON file. It's right there, in the same folder, and yet I can't find a simple way to access it.
I've seen 2 approaches online, one is to put the entire thing in quotes, then add "data=" to the start, and run it like a JS file. This is beyond stupid, but I'll settle for it if I have to.
The other involves making an actual "server" request to my local machine, but when I try that I get an error in chrome, saying that CORS doesn't allow you to access files using request type null. Other people in the comments were saying it was a bad idea to do that.
Is there seriously no easy way to just say "load this file", without jQuery or node?
Simple, fast, but bad for real project solution:
- Rename
myfile.jsontodata.js(name doesn't matter). - Create a variable in data.js and initialize it with your json
var myData = {...your json...} - Add
<script src="./data.js"></script>to your html file. - Now you can use
myDatavariable from javascript with all data.
This solution is bad because you add a new variable in global scope and browser would still make a http request to get this .js file.
Also, If you want to make ajax requests to your local files, you can use http server. Take a look at very simple node js http-server.
This would be a 3 step process.
Move the JSON file into a folder with you other web pages
In the JSON file, give the obejct a name i.e. var data = {...};
In the file that you wan to use it just call it with the <script src='myJSON.js'></script>
Here's a way to do it without jQuery.
First create this function:
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', '../news_data.json', true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(JSON.parse(xobj.responseText));
}
};
xobj.send(null);
}
Then you can use it by simply calling something like this:
loadJSON(function(json) {
console.log(json); // this will log out the json object
});
I found this by simply googling "read local json file javascript" (source)
You can use jQuery.getJSON() in jquery
First add jquery CDN :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
Now set full json file path as ex :- folder/file.json
Description: Load JSON-encoded data from the server using a GET HTTP request.
$.getJSON( "JSON FILE PATH", function( data ) {
console.log(data); //json output
});
DEMO
(function() {
var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
$.getJSON( flickerAPI, {
tags: "mount rainier",
tagmode: "any",
format: "json"
})
.done(function( data ) {
$.each( data.items, function( i, item ) {
$( "<img>" ).attr( "src", item.media.m ).appendTo( "#images" );
if ( i === 3 ) {
return false;
}
});
});
})();
img {
height: 100px;
float: left;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.getJSON demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div id="images"></div>
</body>
</html>
Unfortunately, both XHR and the Fetch API are inextricably tied to HTTP, and cannot be used to load a resource from a relative path unless an HTTP server is involved. If you're loading your page via a file: URL, you won't be able to use XHR or Fetch to get that data.
There are only two methods available to you:
Switch to JavaScript instead of regular JSON and use a
<script>tag (as previously suggested to you in another answer)Allow the user to drag/drop the JSON file (or use
<input type="file">) to get a File reference that you can then load.
I think you are looking for FileReader: https://developer.mozilla.org/en-US/docs/Web/API/FileReader
If you have it working, take a look at JSON.parse(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse