Load JSON file by object value - javascript

I have a slide interface in jQuery that loads a JSON file on each new slide. The JSON files are named with sequential numeric values (1.json, 2.json..) to determine the order of the slides. I would like this to be a value in the object ("index-position") rather than the name of the file.
My question is how would I load these files sequentially in the same manner - but rather than load the order by file name, load them by index position?
My hunch is that this means creating an array of 'index-position' values of all the files and associating each index to a file name, but perhaps there is a simpler/more efficient method?
Thanks

You can read the content of the json before (read the "index-position") and set it to your global array.
Something like:
var slides = [];
$.getJSON( "ajax/fileName.json", function( data ) {
var index = data["index-position"];
slides[index] = data;
}

No magic solution. You must get the files connected to an index in some format (for example ["1.json", "2.json"]). You can put this information in another external file and use it, or you can save an network request by making it hard coded in your code, like this:
var files = ["1.json", "2.json"];

var obj = {};
for (i = 0; i<10; i++)
{
obj[i] = i + ".json";
}
console.log(obj[0], obj[1]);
//0.json, 1.json

Related

update on array elements in javascript file and save it

If I'm reading data "array" from javascript file, and I want to change an element value in the array, how can I apply this update on the javascript file "save the javascript file with new value".
var country = document.getElementById('edit_country').value;
for (i = 0; i < country_arr.length; i++) {
if(country_arr[i] == country) {
var city = "|".concat(document.getElementById("add_city").value);
city_arr[i] = city_arr[i].concat(city);
}
}
You cannot edit a file from a computer with Java Script, the best thing you can do is to create a new file with it and download it. To download a file containing a JSON check this other question: Link

Reading/Writing to a file in javascript

I want to read and write to a file in a specific way.
An example file could be:
name1:100
name2:400
name3:7865786
...etc etc
What would be the best way to read this data in and store in, and eventually write it out?
I don't know which type of data structure to use? I'm still fairly new to javascript.
I want to be able to determine if any key,values are matching.
For example, if I were to add to the file, I could see that name1 is already in the file, and I just edit the value instead of adding a duplicate.
You can use localStorage as a temporary storage between reads and writes.
Though, you cannot actually read and write to a user's filesystem at will using client side JavaScript. You can however request the user to select a file to read the same way you can request the user to save the data you push, as a file.
localStorage allow you to store the data as key-value pairs and it's easy to check if an item exists or not. Optionally simply use a literal object which basically can do the same but only exists in memory. localStorage can be saved between sessions and navigation between pages.
// set some data
localStorage.setItem("key", "value");
// get some data
var data = localStorage.getItem("key");
// check if key exists, set if not (though, you can simply override the key as well)
if (!localStorage.getItem("key")) localStorage.setItem("key", "value");
The method getItem will always return null if the key doesn't exist.
But note that localStorage can only store strings. For binary data and/or large sizes, look into Indexed DB instead.
To read a file you have to request the user to select one (or several):
HTML:
<label>Select a file: <input type=file id=selFile></label>
JavaScript
document.getElementById("selFile").onchange = function() {
var fileReader = new FileReader();
fileReader.onload = function() {
var txt = this.result;
// now we have the selected file as text.
};
fileReader.readAsText(this.files[0]);
};
To save a file you can use File objects this way:
var file = new File([txt], "myFilename.txt", {type: "application/octet-stream"});
var blobUrl = (URL || webkitURL).createObjectURL(file);
window.location = blobUrl;
The reason for using octet-stream is to "force" the browser to show a save as dialog instead of it trying to show the file in the tab, which would happen if we used text/plain as type.
So, how do we get the data between these stages. Assuming you're using key/value approach and text only you can use JSON objects.
var file = JSON.stringify(localStorage);
Then send to user as File blob shown above.
To read you will have to either manually parse the file format if the data exists in a particular format, or if the data is the same as you save out you can read in the file as shown above, then convert it from string to an object:
var data = JSON.parse(txt); // continue in the function block above
Object.assign(localStorage, data); // merge data from object with localStorage
Note that you may have to delete items from the storage first. There is also the chance other data have been stored there so these are cases that needs to be considered, but this is the basis of one approach.
Example
// due to security reasons, localStorage can't be used in stacksnippet,
// so we'll use an object instead
var test = {"myKey": "Hello there!"}; // localStorage.setItem("myKey", "Hello there!");
document.getElementById("selFile").onchange = function() {
var fileReader = new FileReader();
fileReader.onload = function() {
var o = JSON.parse(this.result);
//Object.assign(localStorage, o); // use this with localStorage
alert("done, myKey=" + o["myKey"]); // o[] -> localStorage.getItem("myKey")
};
fileReader.readAsText(this.files[0]);
};
document.querySelector("button").onclick = function() {
var json = JSON.stringify(test); // test -> localStorage
var file = new File([json], "myFilename.txt", {type: "application/octet-stream"});
var blobUrl = (URL || webkitURL).createObjectURL(file);
window.location = blobUrl;
}
Save first: <button>Save file</button> (<code>"myKey" = "Hello there!"</code>)<br><br>
Then read the saved file back in:<br>
<label>Select a file: <input type=file id=selFile></label>
Are you using Nodejs? Or browser javascript?
In either case the structure you should use is js' standard object. Then you can turn it into JSON like this:
var dataJSON = JSON.stringify(yourDataObj)
With Nodejs, you'll want to require the fs module and use one of the writeFile or appendFile functions -- here's sample code:
const fs = require('fs');
fs.writeFileSync('my/file/path', dataJSON);
With browser js, this stackoverflow may help you: Javascript: Create and save file
I know you want to write to a file, but but consider a database instead so that you don't have to reinvent the wheel. INSERT ... ON DUPLICATE KEY UPDATE seems like the logical choice for what you're looking to do.
For security reasons it's not possible to use JavaScript to write to a regular text or similar file on a client's system.
However Asynchronous JavaScript and XML (AJAX) can be used to send an XMLHttpRequest to a file on the server, written in a server-side language like PHP or ASP.
The server-side file can then write to other files, or a database on the server.
Cookies are useful if you just need to save relatively small amounts of data locally on a client's system.
For more information have a look at
Read/write to file using jQuery

downloading a CSV when a condition is satisfied

I have a code which converts JSON to CSV. And I put this through a specific condition ( if condition) I want the CSV to be downloaded automatically if the condition is met without any button click. what is the shortest/simplest way to do this?
For eg:
if( data.length == 10){
var stored_data = data;
data = [];
console.log(stored_data);
var csv_file = ConvertToCSV(stored_data); //ConvertTOCSV is a function
}
if the above condition is met, the CSV should be downloaded. Thank you
NOTE: I know this can e done easily with a button click. but i want the download to happen automatically when the condition is satisfied
Just create a "dummy" link and programmatically set its href and then click. The link shouldn't appear on the screen because it has no content.
<body>
<a href="#" id="csvDownload" download></a>
</body>
<script>
if( data.length == 10){
var lnk = document.getElementById("csvDownload");
var stored_data = data;
data = [];
console.log(stored_data);
var csv_file = ConvertToCSV(stored_data); //ConvertTOCSV is a function
lnk.href = csv_file;
lnk.click();
}
</script>
What you are trying to do is possible by changing the document location to point to your created object, but the problem that I ran into while trying to create a quick example for you, is I can't seem to give the file a usable name and extension. So everything downloaded as a file called "download" with no extension (however - the file contents are correct).
So if you want to pursue finding a way to give the stream a name and file type you could start with something like this -
document.location='data:Application/octet-stream,' +
encodeURIComponent(csv_file);
But I would say that #Scott's answer is a better way to go.

how to load data from text file to javascript array?

i have an array called items=["apple","mango","cherry"];
i wonder how i can load the array data from text file instead of declaring it?the text file data is stored like this "apple","mango","cherry",...
furthermore, how to add to the end of this this text file an item for example add "orange" after "cherry"?
items=["apple","mango","cherry"];
if (items.indexOf(myVariable2) == -1) {
// not found, so output it
t++;
document.myform3.outputtext3.value +=myVariable2+"\n";
}
With jQuery you can do something like this
$.get("textFile.txt", function(data) {
var items = data.split(',');
});
You may need something like this though
var items = data.replace(/"/g, '').split(',');
This is a start.
If this is a user input file then you may need to upload it before you work with it.
Sorry, but I don't believe it's quite that simple. Browsers restrict access to local drives (and to server drives) for security reasons.
But one way to access the text file using jQuery would be
jQuery.get('http://localhost/foo.txt', function(data) {
var myvar = data;
});
var file = event.target.file;
var reader = new FileReader();
var txt=reader.readAsText(file);
var items=txt.split(",");

get remote image into string

The question says it all: how to get a remotely hosted image into a string. I will later use XMLHTTPPost to upload the content. This is javascript question, for those who don't read tag line.
#Madmartigan: the script itself is executed in rather odd manner: user uses javascript: to append the script from the remove host. (this gives access to the user cookie session, which we need in order to proceed) This generates form, giving user ability to setup some texts. (this is easy bit) When user clicks upload the script must get an image hosted on remote host. I am trying to get the image from the remote host as a string and then use something like the function below to convert it to binary. So, how do I do that?
function toBin(str){
var st,i,j,d;
var arr = [];
var len = str.length;
for (i = 1; i<=len; i++){
//reverse so its like a stack
d = str.charCodeAt(len-i);
for (j = 0; j < 8; j++) {
st = d%2 == '0' ? "class='zero'" : ""
arr.push(d%2);
d = Math.floor(d/2);
}
}
//reverse all bits again.
return arr.reverse().join("");
}
I should mention, that I managed to find things like:
var reader = new FileReader();
reader.onload = function() {
previewImage.src = reader.result;
}
reader.readAsDataURL(myFile);
However, they are very browser dependent and therefore not very useful.
I am trying to avoid using base64 because of the redundant size increase.
EDIT: take a look here. Take should help you: http://www.nihilogic.dk/labs/exif/ or maybe here: http://jsfromhell.com/classes/binary-parser the only way to store binary data into string in javascript context is to use base64/base128 encoding. But I never tried it myself to do that in case of a image. There are many JavaScript base encoder/decoder out. Hope this helps you.

Categories