WinJS: Efficient xml parsing - javascript

I currently have the bellow code to get some data from an xml feed.
var title = []
var start = []
var end = []
var xml = result;
var channel = xml.split('<channel')[1].split('>')[0].split('"')[1]
var xmlLength = xml.split("<programme>").length - 1;
for (var i = 0; i < xmlLength; i++) {
var event = xml.split("<event>")[i + 1].split("</event>")[0];
title[i] = programme.split("<title>")[1].split("</title>")[0];
var rs = programme.split("<start>")[1].split("</start>")[0].split(/\-|\s/);
var re = programme.split("<end>")[1].split("</end>")[0].split(/\-|\s/);
start[i] = new Date(rs.slice(0, 3).join('/') + ' ' + rs[3]);
end[i] = new Date(re.slice(0, 3).join('/') + ' ' + re[3]);
}
setListView(event, start, end, channel)
This currently works but it doesn't seem very efficient. I wonder if there is a better way of doing it.

Well, it looks like you should be using the classes in the Windows.Web.Syndication namespace as it looks like you are doing RSS related things, but you could also use the raw XML API's as well.

It seems like you are trying to parse the XML on your own. Have you considered using jQuery.parseXML()?
Check it out here: http://api.jquery.com/jQuery.parseXML/

Related

How to add/append to existing Web storage in javascript?

I am trying to add/append to new/existing localStorage using this code:
function add(){
var name = document.getElementById("name").value;
var ort = document.getElementById("ort").value;
var user = {"name":name, "ort":ort};
var exist = [];
var tmp = (JSON.parse(localStorage.getItem("users")));
if(tmp)
exist.push(tmp);
exist.push(user);
localStorage.setItem("users",JSON.stringify(exist));
console.log(JSON.parse(localStorage.getItem("users")));
var obj = JSON.parse(localStorage.getItem("users"));
for(var i=0; i<obj.length; i++) {
console.log('key: ' + i + '\n' + 'value: ' + obj[i]);
}
}
Looking into Chrome developer tools localStorage looks like this:
[[{"name":"a","city":"a"}],{"name":"b","city":"b"}]
But what I want is:
[{"name":"a","city":"a"},{"name":"b","city":"b"}]
What am I doing wrong?
Any help appreciated,
Best regards,
localStorage only store strings. You need to stringify your exist and then save it to storage
localStorage.setItem("users",JSON.stringify(exist));
To retrieve it use JSON.parse
var exist = JSON.parse(localStorage.exist); //Even for users object do the same
Update
To only push the objects inside the array tmp to exist use map():
tmp.map(function(item){
exist.push(item);
})

Converting JSON to specific string format

I get the following json data from server.
{"visits":[{"City":6,"Count":5},{"City":16,"Count":1},{"City":23,"Count":1},{"City":34,"Count":1}]}
and i need to convert it to following format:
{"1":"82700","2":"26480","3":"31530","4":"22820","5":"15550","6":"205790"}
I have the following code but not working out:
var cities = "{";
for (var key in data.visits) {
var val = data.visits[key];
//Now you have your key and value which you
//can add to a collection that your plugin uses
var obj = {};
obj[val.City] = '' + val.Count;
var code = '' + val.City;
var count = '' + val.Count;
cities += code + ':' + count + ',';
}
cities += "}";
I need the integers in string representation and need to get rid of the final , .
How can i fix this?
Try this
var data = {"visits":[{"City":6,"Count":5},{"City":16,"Count":1},{"City":23,"Count":1},{"City":34,"Count":1}]};
var result = {};
for (var i = 0; i < data.visits.length; i++) {
result[data.visits[i].City] = String(data.visits[i].Count);
}
Example
Keys in object always converts to string you don't need convert it to string manually. If you need convert all object to JSON string you can use JSON.stringify(result);
How I understood you want to create new json with given json.you can parse it,run with cycle on it,and create a new json whatever kind of you want.
here is a link which can help you.
http://www.w3docs.com/learn-javascript/working-with-json.html

eliminating line breaks in an array with javascript and regex

I have a file that looks like so:
QUERY:1
DATABASE:geoquery
NL:What are the capitals of the states that border the most populated states?
SQL:something
QUERY:2
DATABASE:geoquery
NL:What are the capitals of the states bordering New York?
SQL:SELECT state.Capital FROM state JOIN borderinfo ON state.State_Name = borderinfo.State_Name
WHERE borderinfo.Border = 'New York'
QUERY:3
DATABASE:geoquery
NL:Show the state capitals and populations.
SQL:SELECT state.Capital, state.Population FROM state
etc...
The person generating this file refuses to give it to me in a usable format like say, XML or JSON. So I am parsing it a couple of times with REGEX to get results I want.
Strip off Databases to populate select list (works fine):
$.get('inputQueryExamples.txt',
function(data){
var string = data;
var dbDynamo ='';
dbExp = new RegExp('(DATABASE:.*)','gm');
dbDynamo = string.match(dbExp);
cleanBreaks = new RegExp('(\r?\n|\r)','gm');
stringNow = dbDynamo.toString();
//console.log(dbDynamo);
dbDynamo = dbDynamo.map(function(el){return el.replace('DATABASE:','');});
var outArray = [];
for(i=0; i < dbDynamo.length; i++){
if ($.inArray(dbDynamo[i],outArray)== -1){
outArray.push(dbDynamo[i]);
}
}
dbDynamo = outArray.sort();
var options = '';
for(i=0; i<dbDynamo.length; i++){
options += '<option value="' + dbDynamo[i] + '">' + dbDynamo[i] + '</option>';
};
$(select).append(options);
});
The problem comes when I parse a second time to get all of the strings associated with a specific database. I end up with a linebreak in front of every string so that when I fill a textarea with the autocomplete text it starts on the second line:
Array [ "
NL:Show company with complaint against Debt collection product.,DATABASE:consumer", "
NL:Show issues and dates of complaints about HSBC companies.,DATABASE:consumer", "
NL:Show companies, issues and dates with consumer concerns.,DATABASE:consumer", "
NL:Show issues and companies with complaints in MA state." ]
$(document).ready(function(){
$.get('inputQueryExamples.txt',function(data){
var queryString = data;
var cleanString = "";
var db = '';
$('#database-list').change(function(){
db = $('#database-list').val();
// /(^DATABASE:.*\r\n)(^NL.*)/gm
// http://regex101.com/r/mN4hS2
regex = new RegExp('(^DATABASE:'+ db +'\r\n)(^NL.*)' ,'gm');
cleanString = queryString.match(regex);
//console.log(cleanString);
//cleanBreaks = new RegExp('(\r\n|\r|\n)(^NL.*)','gm');
//stringNow = cleanString.toString();
//var dirtyString
//dirtyString = stringNow.match(cleanBreaks);
//console.log(dirtyString);
var nlString = cleanString.map(function(el) {return el.replace('DATABASE:' + db,'');});
nlString = nlString.map(function(el){return el.replace('NL:',''); });
//nlString = nlString.map(function(el){return el.replace('\\r','').replace('\\n','');});
console.log(nlString.pop());
$('#query-list').autocomplete({
source:nlString,
});
}); // end change
I have tried about everything I can think of to get rid of the linebreaks without success. Any ideas would be appreciated. Unfortunately the one where the server side just gives me data in a usable format is not viable. There is a lot of extra code in this just to give you an idea of what I have tried. I have commented out useless things. Thanks in advance.
It would make sense to use JavaScript to parse the data-structure you are given into a JavaScript object first, then you can more easily work with the data.
Here is a jsfiddle that demonstrates parsing your data into a JavaScript object. Below is the relevant code that does the parsing:
var datasources = {};
var parseData = function(block) {
var db = block.match(/DATABASE:(.*)/)[1];
var dbdata = {id: 0, nl: "", sql: ""};
if (!datasources[db]) {
datasources[db] = [];
}
dbdata.id = block.match(/QUERY:(.*)/)[1];
dbdata.nl = block.match(/NL:(.*)/)[1];
dbdata.sql = block.match(/SQL:(.*)/)[1];
datasources[db].push(dbdata);
};
var parseBlocks = function(data) {
var result = data.split('\n\n');
for(var i=0; i < result.length; i++) {
parseData(result[i]);
};
};
Thanks for the very thoughtful and elegant approach. I continued the brute force approach.
replace:
nlString = nlString.map(function(el){return el.replace('NL:',''); });
with:
nlString = nlString.map(function(el){return el.replace('NL:','').trim(); });

Loading an array from local storage: result not an array - javascript [duplicate]

This question already has answers here:
How to store objects in HTML5 localStorage/sessionStorage
(24 answers)
Closed 8 years ago.
I have several large multi-dimensional arrays that I'm saving to local storage. They look like this:
[[[-150],[0],[-650],0],[[-100],[0],[-650],0],[[-50],[0],[-650],0] ... ]
The data is '4D' data. When I try loading this 'string' into an array in another JS (in separate html), it doesn't behave like an array- it's only a string.
Here's how I load the data back into the second JS (not sure why the loop didn't work either):
var lay= new Array();
//for(var g=0;g>=9;g++)
//{ lay[g] = localStorage.getItem("key" + g);
// console.log(lay[g]);
//}
lay[0] = localStorage.getItem("key0");
lay[1] = localStorage.getItem("key1");
lay[2] = localStorage.getItem("key2");
//... more here
lay[9] = localStorage.getItem("key3");
After I load this "4D" info into the array, I pull the info out to use it:
var count=0;
var len=0;
for (y=0;y<=1;y++)
{ console.log(lay[y]);
count=1;
len = lay[y].length;
for (x=1;x<=len-1;x++)
{
Rx = lay[y][count][0];
Ry = lay[y][count][1];
Rz = lay[y][count][2];
Rcolor = lay[y][count][3];
When I add this to the code console.log(len); I get the length of characters in the array, not the number of elements. How can I get the data from local storage to come in and behave like array? I thought that the formatting alone would get it behave like an array.
Do I need to parse it back into an array again? If so, I'm guessing I should just output the data in a simpler format to parse it again...
Thanks for the help!
Edit
Here's how I made the local storage:
for (var a=0;a<=14;a++)
{ updateTemp(tStep + a);
$("#temp tbody tr").each(function(i, v){
data[i] = Array();
$(this).children('td').each(function(ii, vv){
data[i][ii] = $(this).text();
rows=ii;
cols=i;
});
});
retval="";
for (var q=0;q<=cols;q++)
{
for (var w=0;w<=rows;w++)
{
var tempv = data[q][w];
var tX = w*50 - 1000;
var tY = 1*50 - 50;
var tZ = q*50 - 1000;
if (tempv==-9){
(dummy=q*w);
}
else {retval += tX +',' + tY + ',' + tZ + ',' + tempv + ',';}
}
}
var kee = "key" + a;
retval = retval.substring(0, retval.length-1); //this is to get rid of the last character which is an extra ,
window.localStorage.setItem(kee, retval);}
JSON encode the array before storing, parse after retrieving.
localStorage.test = JSON.stringify([1,2,3]);
console.log(JSON.parse(localStorage.test));
This is a duplicate of “Storing Objects in HTML5 localStorage”. localstorage only handles strings. As suggested there, serialise your array to a JSON string before storing.

Unable to Split the array element in Javascript

I am quite new to Javascript. I wanted to get the filename and extension from a specific folder. For that i am using ActiveXObject and going to the folder using GetFolder and then enumerating through each individual files. The code is given below.
<html>
<script type='text/javascript'>
var myFileNameArray = new Array;
var myFileNameArray = new Array;
function ReadFromFile()
{
var i;
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fsofolder = fso.GetFolder("C:\\Users\\Divya.R");
var colFiles = fsofolder.Files;
var fc = new Enumerator(colFiles);
for (; !fc.atEnd(); fc.moveNext() )
{
msg += fc.item() + ";";
}
myFilePathArray = msg.split(";");
for(i=0;i<=myFilePathArray.length;i++)
{
myFileNameArray[i] = myFilePathArray[i].split("\\");
}
document.write(myFileNameArray[0]);
}
</script>
<body onload='ReadFromFile()'>
</body>
</html>
I will get the complete file path in myFilePathArray from each array element i should get the filename. For that I am trying to split again based on '/' and then thought to get the arraylength-1 th element. However the last document write return be a blank page. It doesnt split the myFilePathArray. Please let me know what is wrong with this.
Regards,
Div
Since \ is an escape character it will be ignored. I have found a solution which worked for me. The code is given below.
var msg = "C:\\Users\\Divya.R\\Data.txt;C:\\Users\\Divya.R\\Test2.csv";
var regex = /\\/g;
var fileName="";
var FilePath = msg.replace(regex, "\\\\");
//document.write(FilePath);
var myArray1 = new Array;
var myArray2 = new Array;
myArray1 = FilePath.split(";");
myArray2 =myArray1[0].split("\\");
for(var i=0;i<=myArray1.length-1;i++)
{
myArray2= myArray1[i].split("\\");
fileName = fileName+myArray2[myArray2.length-1];
}
//alert(myArray2[myArray2.length-1]);
alert(fileName);
Regards,
Divya
A simple substr and lastIndexOf would suffice to get your parts:
var path = "C:\\Users\\Divya.R\\Data.txt";
var fileName = path.substr(path.lastIndexOf("\\") + 1);
var ext = path.substr(path.lastIndexOf('.') + 1); // txt

Categories

Resources