I want to load multiple .json files to an array, but I don't know the exact amount of files.
E.g.:
(in: .../example-folder)
abc.json
xyz.json
uvw.json
array.length == 3
(in .../example_folder)
abc.json
xyz.json
array.length == 2
How could I do that in javascript?
Thanks in advance!
Kind regards,
Soxxes
Edit:
Normally I am doing it this way:
function loadJSON(url, callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType('application/json');
xobj.open('GET', url, true);
xobj.onreadystatechange = function() {
if (xobj.readyState == 4 && xobj.status == '200') {
callback(xobj.responseText);
}
};
xobj.send(null);
}
loadJSON("../example_folder/abc.json", function(res){
data_parsed = JSON.parse(res);
data_stringified = JSON.stringify(data_parsed, null, 4);
abc = data_stringified;
});
You can create an API to return a number of JSON files or a list of them. If you don't want to create that API, just put expected response to a specific JSON file.
// api.json
{
"files": [ "abc.json", "xyz.json" ]
}
Related
I've got a text file 'mytext.txt' with IPs and some text seperate by commas in different lines -
24.16.153.165:51413,abc
67.185.72.127:51413,xyz
69.247.183.46:63303,pqr
130.56.220.16:6881,def
I want to store the IPs in an array in JavaScript to plot them on a map. I found a way to do this by using a static array -
var map = new google.maps.Map(document.getElementById('map'), googleMap);
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(infowindow, "closeclick", function() {
map.fitBounds(latlngbound);
map.panToBounds(latlngbound)
})
var ipArray = ["70.177.167.189", "123.135.107.115", "123.135.107.115", "123.135.107.115", "123.135.107.115", "122.182.6.19", "24.19.187.145", "24.19.187.145", "27.251.20.130", "27.251.20.130"];
ipArray.forEach((ip) => {
addIPMarker(ip);
})
} catch(e){
//handle error
}
Can someone tell me how to do it after extracting the IPs from the text file? It should be a fairly simple logic, but I'm not very familiar with JavaScript. Thanks!
This function works if you have a file on the server or another url.
function loadDoc() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = this.responseText;
var data = myObj.split(/\n/g);
var data_ip = [];
for(item in data)
{
var ip = data[item].split(/,/g);
data_ip.push(ip[0]);
}
console.log(data_ip);
}
};
xmlhttp.open("GET", "file.txt", true);
xmlhttp.send();
}
And this was work with a locally stored file.
function readTextFile(file)
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var myObj = rawFile.responseText;
var data = myObj.split(/\n/g);
var data_ip = [];
for(item in data)
{
var ip = data[item].split(/,/g);
data_ip.push(ip[0]);
}
console.log(data_ip);
}
}
}
rawFile.send(null);
}
readTextFile("file:///C:/your/path/to/file.txt");
To read a file in from your system you need to use the fs (file system) module provided by Node. You won't need to do any npm install.
JavaScript file:
const fs = require('fs');
const mapData = fs.readFileSync(//path to file here);
// do things with the data like your ip mapping, etc...
I have used the fs.readFileSync() function in the example but you will want to read the documentation and see what works best for your application.
Documentation:
https://nodejs.org/api/fs.html
This is my problem because I never used json, always just database or objects in javascript.
I don't want JQUERY I need just plain javascript!
But now when I try to fetch some data from json file I get empty response:
function loadJSON(file, callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', file, true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200"){
callback(xobj.responseText);
}
};
xobj.send(null);
}
function load(){
loadJSON("data.json", function(response) {
var some_data = JSON.parse(response);
console.log(some_data);
});
}
data.json contains:
{"cars":["Mazda", "BMW"],"myCar":"BMW"}
Basically I want to fetch cars and do something with it...
When I use object in javascript it is very easy but as I said I never used json so I really do not know what are problems in my code.
I have an html file with just a table, containing 5 cells in a single row, displaying 5 NFL teams.
The td's ids are "Team0" to "Team4" (left to right).
My purpose is to move a double clicked team to the last position in the right (to the cell wich id is "Team4").
In every td I have a call to Rearrange_Teams(iPosition).
iPosition is the number in the td id (Team3 calls Rearrange_Teams(3).
The following code works fine, but I'd like to change the function Load_Teams(), in order to load the teams from a file in my desktop (where my html file is saved):
<script>
Array.prototype.Rearrange = function(from,to){
this.splice(to,0,this.splice(from,1)[0]);
return this;
};
var aTeams = [];
Load_Teams();
List_Teams();
function Load_Teams() {
aTeams [0] = "PANTHERS";
aTeams [1] = "CARDINALS";
aTeams [2] = "BENGALS";
aTeams [3] = "BRONCOS";
aTeams [4] = "PATRIOTS";
}
function List_Teams() {
document.getElementById("Team0").innerHTML = aTeams [0];
document.getElementById("Team1").innerHTML = aTeams [1];
document.getElementById("Team2").innerHTML = aTeams [2];
document.getElementById("Team3").innerHTML = aTeams [3];
document.getElementById("Team4").innerHTML = aTeams [4];
}
function Rearrange_Teams(iPosition_Clicked) {
aTeams.Rearrange(iPosition_Clicked,4);
List_Teams();
}
</script>
Both the html page and the data file (JSON? txt?) are supposed to be saved in my computer (desktop or user directory, whatever...).
I just can't find an answer to help me with this... well, at least I can't understand the changes I'd have to make in the codes I've seen around...
The idea is to save the changes in the list, so I have to load the previous configuration and save the actual ones...
It's not possible to set up a local webserver, as I was suggested before, cause the intention is to use this page at my work and the users don't have administrator privileges (myself included).
We currently use an Excel worksheet with VBA, to get the job done, but I want to change it to the browser.
EDITED AFTER REPLY:
I've tried:
function Load_Teams() {
var actual_JSON;
loadJSON("My_File_with_Data.json", function(response) {
actual_JSON = JSON.parse(response);
});
alert(actual_JSON);
}
function loadJSON(filename, callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', filename, true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(xobj.responseText);
}
};
xobj.send(null);
}
But nothing happened...
The alert(actual_JSON) shows nothing (just a blank pop up, with an "ok").
And I have no idea how I should pass the content of actual_JSON (does it really have any???) to aTeams.
The file My_File_with_Data.json looks like this:
{"jTeams": ["PANTHERS","CARDINALS", "BENGALS", "BRONCOS", "PATRIOTS"]}
NEW APPROACH:
var aTeam = [];
readTextFile();
List_Teams();
function readTextFile(){
var rawFile = new XMLHttpRequest();
rawFile.open("GET", "Teams.txt", true);
rawFile.onreadystatechange = function (){
if(rawFile.readyState === 4){
var allText = rawFile.responseText;
aTeam = allText.split("/");
alert(aTeam[4]);
}
}
rawFile.send();
}
function List_Teams() {
document.getElementById("Team0").innerHTML = aTeam[0];
document.getElementById("Team1").innerHTML = aTeam[1];
document.getElementById("Team2").innerHTML = aTeam[2];
document.getElementById("Team3").innerHTML = aTeam[3];
document.getElementById("Team4").innerHTML = aTeam[4];
}
The file Teams.txt looks like:
PANTHERS/CARDINALS/BENGALS/BRONCOS/PATRIOTS
When readTextFile() runs, the alert(aTeam[4]) displays PATRIOTS.
But List_Teams() fills my table with undefined.
How come??? Seems to be a matter of scope, but aTeam is a global!...
A slightly modified version of code from this blog post, here is a function you can use to load JSON:
function loadJSON(filename, callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', filename, true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
// Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
callback(xobj.responseText);
}
};
xobj.send(null);
}
to use this function, you need a callback:
var actual_JSON;
loadJSON("localhost:8000/my-file", function(response) {
// Parse JSON string into object
actual_JSON = JSON.parse(response);
});
alert(actual_JSON);
replace /my-file with a path to your file.
You also need a server at the location, which you can set up quickly like this
I am working loading a JSON file from a relative local path into my web based app. To do this I am using an XMLHttpRequest object, as following:
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'myFyle.json', true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(JSON.parse(xobj.responseText));
}
}
xobj.send(null);
My issue is that I can't manage the browser error (net::ERR_FILE_NOT_FOUND) when myFyle.json is not found. I would like to load an standard .json file (e.g. myStandardFile.json) when this happens.
Does anybody has an idea to do this?
Thanks in advance!
Pedro.
You can use xobj.status === 404 to detect 'file not found'.
The web site hosting server will typically generate a "404 Not Found"
web page when a user attempts to follow a broken or dead link;
In case of 404 you can load your default file like this:
function load(file, callback) {
var defaultFile = "myStandardFile.json";
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', file, true);
xobj.onreadystatechange = function() {
if (xobj.readyState !== 4) return true;
if (xobj.status === 200) {
callback(JSON.parse(xobj.responseText));
//File not found.
//The second condition just to prevent endless calls
//in case if your default file doesn't exist
} else if (xobj.status === 404 && file !== defaultFile) {
load(defaultFile, callback);
}
}
xobj.send(null);
}
load("myFyle.json", function(data) {
console.log(data);
})
Demo:
function load(file, callback) {
var defaultFile = "https://httpbin.org/user-agent";
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', file, true);
xobj.onreadystatechange = function() {
if (xobj.readyState !== 4) return true;
if (xobj.status === 200) {
callback(JSON.parse(xobj.responseText));
//File not found
} else if (xobj.status === 404 && file !== defaultFile) {
load(defaultFile, callback);
}
}
xobj.send(null);
}
load("https://httpbin.org/inexistentFile.json", function(data) {
console.log(data);
})
I hope this will help you.
I am attempting to load a JSON file from javascript but i keep getting the following error even though the path is correct
[HTTP/1.1 404 Not Found 2ms]
this is the code i am using to load it
loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'Assets/test.json', true); // Replace 'my_data' with the path to your file
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == 200) {
// Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
callback(xobj.responseText);
}
};
xobj.send(null);
}
window.onload = function () {
var canvas = <HTMLCanvasElement> document.getElementById('Can');
context = canvas.getContext('2d');
load = new preload.AtlasLoader();
load.loadJSON(init);
}
function init(response) {
image2 = JSON.parse(response);
}
thanks in advance
i found the answer in this thread:
https://stackoverflow.com/questions/19516829/allow-loading-of-json-files-in-visual-studio-express-2013-for-web
it was a configuration issue with IIS and you just need to add the lnes posted in the answer in that question.