My code is very simple: I'm trying to parse the following XML: https://www.chilkatsoft.com/xml-samples/bookstore.xml
But when I try to print data, I obtain an array of null (however the length is correct).
Any suggestions? Thanks in advance!
xhr.onload = function() {
var xml = this.responseXML;
//get the book nodelist from our response xml object
var items = xml.documentElement.getElementsByTagName("book");
//create empty data array
var data=[];
//loop each book in the xml
for (var i = 0; i < items.length; i++) {
//obtain the title
var str=items.item(i).getElementsByTagName("title").item(0).text;
//add the title to our data array
data.push(str);
}
console.log(data);
};
Solved:
var lng = endLocation.getElementsByTagName('lng').item(0).childNodes.item(0).nodeValue;
instead of:
var lng = endLocation.getElementsByTagName('lng').item(0).text;
Related
I have JSON stringify data like this :
[{"availability_id":"109465","date":"2017-02-21","price":"430000"},{"availability_id":"109466","date":"2017-02-22","price":"430000"},{"availability_id":"109467","date":"2017-02-23","price":"430000"}]
I want to get only price value of that data. I have tried this way but it doesn't work.
var stringify = JSON.stringify(values);
for(var i = 0; i < stringify.length; i++)
{
alert(stringify[i]['price']);
}
How could I to do that ?
This code will only fetch the price details.
var obj = '[{"availability_id":"109465","date":"2017-02-21","price":"430000"},{"availability_id":"109466","date":"2017-02-22","price":"430000"},{"availability_id":"109467","date":"2017-02-23","price":"430000"}]';
var stringify = JSON.parse(obj);
for (var i = 0; i < stringify.length; i++) {
console.log(stringify[i]['price']);
}
Observation :
If you want to parse the array of objects to get the property value you have to convert in into JSON object first.
DEMO
var jsonStringify = '[{"availability_id":"109465","date":"2017-02-21","price":"430000"},{"availability_id":"109466","date":"2017-02-22","price":"430000"},{"availability_id":"109467","date":"2017-02-23","price":"430000"}]';
var jsonObj = JSON.parse(jsonStringify);
for(var i = 0; i < jsonObj.length; i++)
{
alert(jsonObj[i]['price']);
}
you will geting a stringified object like this
var obj='[{"availability_id":"109465","date":"2017-02-21","price":"430000"},
{"availability_id":"109466","date":"2017-02-22","price":"430000"},
{"availability_id":"109467","date":"2017-02-23","price":"430000"}]';
parse your obj using JSON.parse(object)
then apply this loop ad let me know it get any error
lie this
var parseObject = JSON.parse(object);
instead of using stringify before selecting the data you should use your loop directly on the values array.
For example :
var priceArray = array();
values.forEach (data) {
alert(data['price'];
priceArray.push(data['price']);
}
stringify = JSON.stringify(values);
stringifiedPriceArray = JsON.stringify(priceArray);
Once stringified, you can't reach the data in your array
I'm trying to create a bar chart using AmCharts using an array that is part of a larger JSON object that is being retrieved from localStorage. Basically, what I do is retrieve the JSON string, parse it back to JSON object, search take the specific array I'm dealing with ("results"), search that array for the result I'm looking for (via "id"), and then take the array I need ("scores") from that specific result. Then, I use that array as the input for the AmChart code.
I've tested the AmChart code with another sample array (defined in the code) and it works fine. However, when I try to retrieve from localStorage, I am unable to get the chart to display. Any thoughts as to why? The code in question is here:
//retrieve initial results response from localstorage
var search_results = localStorage.getItem("results_response");
//convert retrieved string back to JSON array
var search_results_object = JSON.parse(search_results); //search_results_objects is now a JSON array
var results = search_results_object.results; //pull out results array
//get venue_id of detail page from local storage
var ven_id = localStorage.getItem("country_id");
//search JSON response for venue ID
var chartDataResults = [];
var searchField = "id";
var searchVal = ven_id;
for (var i=0 ; i < results.length ; i++)
{
if (results[i][searchField] == searchVal) {
chartDataResults.push(results[i]);
}
}
var chartDataInput = chartDataResults.scores;
//this all works:
var chartData = chartDataInput;
var chart = new AmCharts.AmSerialChart();
chart.dataProvider = chartData;
chart.categoryField = "country";
chart.rotate = true;
var graph = new AmCharts.AmGraph();
graph.valueField = "score";
graph.type = "column";
chart.addGraph(graph);
var categoryAxis = chart.categoryAxis;
categoryAxis.autoGridCount = false;
categoryAxis.gridCount = chartData.length;
categoryAxis.gridPosition = "start";
categoryAxis.labelRotation = 90;
graph.fillAlphas = 0.8;
chart.write('chartdiv');
Most recently, the dev console in Chrome has told me "Uncaught TypeError: Cannot read property 'length' of undefined". The chart does not render, either. Thoughts? I appreciate any and all help.
Your code fails because of this:
var chartDataInput = chartDataResults.scores;
chartDataResults is an array by your declaration, not an object. According to the amDocs you could pass chartDataResults directly, given that it is in the correct format, eg [{title:"sample 1",value:130},{title:"sample 2",value:26}];.
If so - try to replace:
var chartDataInput = chartDataResults.scores;
//this all works:
var chartData = chartDataInput;
with
var chartData = chartDataResults;
If you chartDataResults array is not in the correct format, you need to construct it in that loop. Something like:
for (var i=0 ; i < results.length ; i++) {
if (results[i][searchField] == searchVal) {
var aResult = new Object();
aResult.title = results[i].title; // or results[i]['title']
aResult.value = parseInt(results[i].value); // or results[i]['value']
chartDataResults.push(aResult);
}
}
I am speculating that in your json objects you have .title and .value. If not - replace them accordingly. If you're not sure :) what properties they have - print them to the console and inspect them.
I am trying to parse forex values (all of them) for http://indicador.eof.cl/rss XML feed into a Gooogle Sites trough Google Apps Script.
The script as follow>
function doGet(){
var response = UrlFetchApp.fetch("http://indicador.eof.cl/rss").getContentText();
var parsedResponse = Xml.parse(response, false);
var root = parsedResponse.getElement();
var entries = root.getElement('channel').getElements("item");
for (var i=0; i<entries.length; i++) {
var e = entries[i];
var title = e.getElement("title").getText();
var description = e.getElement("description").getText();
}
var app = UiApp.createApplication();
var TopVar = app.createHorizontalPanel();
TopVar.add(app.createLabel(title).setStyleAttribute("fontSize","12px"));
TopVar.add(app.createLabel(description).setStyleAttribute("fontSize","12px"));
app.add(TopVar);
return app;
}
The issue is the code just bring me the first value no all of them, what i am forgetting?
Best Regards,
Try to move TopVar.add(...); lines inside for loop :
var app = UiApp.createApplication();
var TopVar = app.createHorizontalPanel();
for (var i=0; i<entries.length; i++) {
var e = entries[i];
var title = e.getElement("title").getText();
var description = e.getElement("description").getText();
TopVar.add(app.createLabel(title).setStyleAttribute("fontSize","12px"));
TopVar.add(app.createLabel(description).setStyleAttribute("fontSize","12px"));
}
Actually, I know nothing about google-apps-script. But your current code logic seems a bit off. It doesn't make use of values of local variables declare inside for loop (e, title, and description). Value of those variables changed in every iteration without any code using it.
I need create Javascript array from xml ..
I`v get xml data from poly php with ajax. Everything is ok.
I must create array like that:
point = [
new google.maps.LatLng(40.9921196514,47.8604733650 ),
new google.maps.LatLng(40.9922511293,47.8606186245 ),
];
Code
downloadUrl("poly.php", function(data) {
var xml = data.responseXML;
var polys = xml.documentElement.getElementsByTagName("poly");
for (var i = 0; i < polys.length; i++) {
var pid = polys[i].getAttribute("pid");
point = [
new google.maps.LatLng(parseFloat(polys[i].getAttribute("plat")), parseFloat(polys[i].getAttribute("plng")) );
];
i`ve do that but it does not work.. ((
P.S. I get data from MySQL.
...
Xml:
<polys>
<poly pid="1" pstatus="status1" plat="40.992638" plng="47.860474"/>
<poly pid="2" pstatus="status2" plat="40.992252" plng="47.860619"/>
</polys>
May I assume you use the function downloadUrl from googles util.js ?
When yes: data is already a document, there is no need to access data.responseXML
Each attempt to access a property of xml will result in an error, because xml is undefined
Replace this:
var xml = data.responseXML;
var polys = xml.documentElement.getElementsByTagName("poly");
with:
var polys = data.documentElement.getElementsByTagName("poly");
There is an syntax-error:
point = [
new google.maps.LatLng(parseFloat(polys[i].getAttribute("plat")), parseFloat(polys[i].getAttribute("plng")) );
];
remove the semicolon:
("plng")) );
//---------^
But to get the desired result you must create the point-array outside the loop:
var point=[];
and add the LatLng's to point inside the loop:
point.push(new google.maps.LatLng(parseFloat(polys[i].getAttribute("plat")),
parseFloat(polys[i].getAttribute("plng"))));
what I want to do is access an excel file, take the contents of a column and then store it in an array. I'm guessing this can be done by iterating through each element of the range object and copying it to an array. My current code is shown below:
function GetData(){
var excel = new ActiveXObject("Excel.Application");
var excel_file = excel.Workbooks.Open("C:\\Data.xls");
var excel_sheet = excel.Worksheets("Sheet2");
//returns a RANGE object
var myrow = excel_sheet.Columns(1);
//doing this puts a single range object in myarray
var myarray = new Array(myrow);
//try printing the contents of the range object
for (mycell in myrow){
document.getElementById('div1').innerHTML = mycell;
}
}
Please check the following code to get data from an excel file. Hope this helps you:
CODE:
function GetData(){
var excel = new ActiveXObject("Excel.Application");
var excel_file = excel.Workbooks.Open("C:\\Data.xls");
var excel_sheet = excel.Worksheets("Sheet2");
for(var i=2;i<20;i++){
var myrow = excel_sheet.Range("A"+i); //to read values in row A
document.getElementById('div1').innerHTML = myrow;
}
}
Tested in IE9.