Read variables from a file in Javascript - javascript

I have a variable called words in Javascript like this:
var words = [{"text":"This", "url":"http://google.com/"},
{"text":"is", "url":"http://bing.com/"},
{"text":"some", "url":"http://somewhere.com/"},
{"text":"random", "url":"http://random.org/"},
{"text":"text", "url":"http://text.com/"},
{"text":"InCoMobi", "url":"http://incomobi.com/"},
{"text":"Yahoo", "url":"http://yahoo.com/"},
{"text":"Minutify", "url":"http://minutify.com/"}]
and I use the variable elements as for example words[0].url which points to the first url, i.e http://google.com/, etc.
If I store the data in a file like this (I call it file.csv):
This, http://google.com/
is, http://bing.com/
some, http://somewhere.com/
random, http://random.org/
text, http://text.com/
InCoMobi, http://incomobi.com/
Yahoo, http://yahoo.com/
Minutify, http://minutify.com/
How can I read the file in Javascrip and re-create variable words, with the exact same format as I mentioned earlier, i.e re-create:
var words = [{"text":"This", "url":"http://google.com/"},
{"text":"is", "url":"http://bing.com/"},
{"text":"some", "url":"http://somewhere.com/"},
{"text":"random", "url":"http://random.org/"},
{"text":"text", "url":"http://text.com/"},
{"text":"InCoMobi", "url":"http://incomobi.com/"},
{"text":"Yahoo", "url":"http://yahoo.com/"},
{"text":"Minutify", "url":"http://minutify.com/"}]

It looks like there are two steps. First is to get the external file, and the next step is to get it into a format you want it.
If you're not using jquery, first step is:
var file = new XMLHttpRequest();
file.onload = function() {
alert(file.responseText);
}
file.open('GET', 'file.csv');
file.send();
Next step is to take that file.responseText and format it. I might do:
var file = new XMLHttpRequest();
var words = [];
file.onload = function() {
var lines = file.responseText.split("\n");
for (var i = 0; i < lines.length; i++) {
var word = {};
var attributes = lines[i].split(",");
word.text = attributes[0];
word.url = attributes[1];
words.push(word);
}
}
file.open('GET', 'file.csv');
file.send();
If you're using a JSON file, just change the function above to be:
file.onload = function() {
words = JSON.parse(file.responseText);
}
Keep in mind that the words variable will not be available until the onload function runs, so you should probably send it to another function that uses it.

You could use the fetch API, it has many advantages and one of them is very short syntax, unlike the XMLHttpRequest constructor.
fetch("object.json").then(function(data){window.data=data.json()});
//then access the data via [window.data]

Related

Data erase in an array

I'm new in code with Javascript and I have a problem with an array I need to create.
var tabLine = new Array();
var tabCol = new Array();
var tabComplet = new Array();
var fso, f1, ts, s, cl, ln;
var ForReading = 1;
var i = 0;
function ReadFiles() {
fso = new ActiveXObject("Scripting.FileSystemObject");
// Read the contents of the file.
ts = fso.OpenTextFile("PathToAFile\TextFile.txt", ForReading);
s = ts.ReadAll();
tabLine = s.split('\n');
cl = tabLine.length;
ts.Close();
for (i = 0; i <tabLine.length; i++) {
var tabCol = tabLine[i].split("\t");
for (j=0;j<tabCol.length;j++) {
tabComplet[i,j] = tabCol[j];
alert(tabComplet[i,j]);
}
}
alert(tabComplet[10,5]);
alert(tabComplet[3,5]);
}
ReadFiles();
The file I need to read is a text file; It have many line and each line have information separate by tabulation.
This function read the text file and convert it into an array in two dimensions.
I had some alert to check the contain of my array.
The first alert give me the result I want (it display the content of the array witch is different for each element in the array)but the two other give me the same result. I check with another alert and, in the for boucle, these two element are different.
I make more test and all happen like if my array only have the same line copy/paste.
Thanks in advance for all information that can help me.
Here is an example of file I use :
http://www.k-upload.fr/afficher-fichier-2017-05-18-1b0cfa685testimport2.txt.html
Usually there are bigger than this one but for test it's OK.

How can I assign a JavaScript variable by parsing a JSON file?

I have a database server that will be running a script to generate this given file daily:
{"data": [
{"variable":"var1","value": "123"},
{"variable":"var2","value": "456"},
{"variable":"var3","value": "789"}]}
I am trying to parse this file to set three javascript variables for a HTML canvas element.
So far, I'm thinking I'll parse the JSON file
var JSONfile = './file.json';
var getData = JSON.parse(JSONfile);
Then a for loop to assign the variables
for (i = 0; i < getData.length; i++) {
var getData.variable=getData.Value;
}
And I'm hoping to get results of:
var var1 = 123;
var var2 = 456;
var var3 = 789;
But var getData.variable=getData.Value; breaks. What am I missing?
JSON.parse() expects a JSON string, when you are passing it a file.
The first thing you need to do is use AJAX to get the contents of the file into a variable. Either use a library like jQuery (see http://api.jquery.com/jquery.getjson/) or from scratch in JavaScript. But don't waste your time on the "from scratch" version unless you have to.
Use jQuery to get the contents of the file into an object, and pass the inner data (an array) to a function called doSomething():
$(function () {
$.getJSON("./file.json", function (data) {
}).success(function (data) {
myArr = data.data;
doSomething(data.data);
});
});
Here, you iterate through the passed array, which contains elements that have a .variable and a .value property. This writes both properties of each element to the console, for your viewing pleasure:
function doSomething(arr) {
for (i = 0; i < arr.length; i++) {
console.log(arr[i].variable + ': ' + arr[i].value);
}
}
You can also access the properties directly by the index as follows:
alert(jsonFromFile.data[2].variable); // Will alert "var3"
alert(jsonFromFile.data[2].value); // Will alert "789"

javascript: how to pass an array argument from an in-html script to an external JS function

I'm pretty new at Javascript (and web design). I'm trying to design an interactive webgame for purely educational purposes (I'm a professional educator. Most of my programming experience in creating self-contained Java apps).
In my HTML document, I have some internal script that creates a boolean array called hypotheses. I also have an external JS script called game.js that produces some visual output based on its own array, also called hypotheses, which I call using . I would like to update the external array from the internal one, but nothing I try works. The internal script is called from a form.
<script>
var testedhypotheses = [];
var hypotheses = hypArray(); //load up a boolean array of hypotheses.
function testHypothesis(theform, numTest){
//update numbers
theform.newhyp.value = theform.newhyp.value - numTest;
//move hypotheses from one list to the other
for(var i; i < numTest; i++){
testedHypotheses.push(hypotheses.pop());
}
//pass the array of hypotheses to the external function.
updateHyp(testedHypotheses);
</script>
The function definitely works, and items are being moved from one array to another. However, the function updateHyp() is not being called. I've tried it a bunch of ways, but the most recent was to include this in the HTML file:
<script type="text/javascript" src="game.js">
var updateHyp = function (hypArray) {
updateHypotheses(hypArray);
};
</script>
Inside game.js, I have the following code:
var updateHypotheses = function(hypArray){
var end = hypotheses.length;
for(var i = end; i < hypArray.length; i++){
var ind = hypotheses.length;
var tf = hypArray[i];
var rando = Math.random();
var res rando < 0.5 ? 1 : 0;
hypotheses.push(new Hypothesis(i, tf, res));
}
}
};
It seems that this code is never getting called. Any help would be much appreciated!!!

Grab YouTube ID and additional variables for embedding purposes with JavaScript

So I've seen lots of scripts to grab the YouTube ID from a URL with JavaScript, but I can't find or figure out how to grab the ID along with any additional variables. I have a PHP script which can do it, but I'd like to do this with JavaScript. Does anyone know how this can be accomplished?
I doubt it's necessary but here are the two scripts I'm using
JavaScript for video ID...
url = $(this).text();
var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=)([^#\&\?]*).*/;
var match = url.match(regExp);
if (match&&match[2].length==11){
alert(match[2]);
}else{
alert("not youtube");
}
And PHP...
if (preg_match('%(?:youtube\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match)) {
$youtubeid = $match[1];
$getyt = (parse_url($url));
}
if(strlen($getyt['fragment']) > 0) {
$addhash = '#' . $getyt['fragment'];
}
$embed = "http://www.youtube.com/embed/$youtubeid?wmode=opaque&autoplay=1$addhash";
The PHP one is pretty good, except that it only works for hash tags. My primary reason for wanting the additional variables is for when someone wants to specify a start time. So if anyone can tell me how I can grab the URL and additional paramaters (or just the specified starting time of the video) then I'd really appreciate it, because I'm absolutely lost.
This creates an associative array named video_parameters:
function extractParameters(url)
{
var query = url.match(/.*\?(.*)/)[1];
var assignments = query.split("&")
var pair, parameters = {};
for (var ii = 0; ii < assignments.length; ii++)
{
pair = assignments[ii].split("=");
parameters[pair[0]] = pair[1];
}
return parameters;
}
url = "http://www.youtube.com/watch?v=gkU&list=UUa3Q&feature=plcp";
video_parameters = extractParameters(url);
// video_parameters["v"]
// > "gkU"
// video_parameters["list"]
// > "UUa3Q"
See How can I get query string values in JavaScript? for methods that handle special chars.

Get Query String with Dojo

Users will be hitting up against a URL that contains a query string called inquirytype. For a number of reasons, I need to read in this query string with javascript (Dojo) and save its value to a variable. I've done a fair amount of research trying to find how to do this, and I've discovered a few possibilities, but none of them seem to actually read in a query string that isn't hard-coded somewhere in the script.
You can access parameters from the url using location.search without Dojo Can a javascript attribute value be determined by a manual url parameter?
function getUrlParams() {
var paramMap = {};
if (location.search.length == 0) {
return paramMap;
}
var parts = location.search.substring(1).split("&");
for (var i = 0; i < parts.length; i ++) {
var component = parts[i].split("=");
paramMap [decodeURIComponent(component[0])] = decodeURIComponent(component[1]);
}
return paramMap;
}
Then you could do the following to extract id from the url /hello.php?id=5&name=value
var params = getUrlParams();
var id = params['id']; // or params.id
Dojo provides http://dojotoolkit.org/reference-guide/dojo/queryToObject.html which is a bit smarter than my simple implementation and creates arrays out of duplicated keys.
var uri = "http://some.server.org/somecontext/?foo=bar&foo=bar2&bit=byte";
var query = uri.substring(uri.indexOf("?") + 1, uri.length);
var queryObject = dojo.queryToObject(query);
//The structure of queryObject will be:
// {
// foo: ["bar", "bar2],
// bit: "byte"
// }
In new dojo it's accessed with io-query:
require([
"dojo/io-query",
], function (ioQuery) {
GET = ioQuery.queryToObject(decodeURIComponent(dojo.doc.location.search.slice(1)));
console.log(GET.id);
});
Since dojo 0.9, there is a better option, queryToObject.
dojo.queryToObject(query)
See this similar question with what I think is a cleaner answer.

Categories