how to parse JSON Response(Data) in javascript. - javascript

i am little new to javascript..Can anyone help me out from here.My JSON Response is like below:And i want to parse it and show it in the Table.
And my javascript code is below:
function parseData() {
var xmlhttp = new XMLHttpRequest();
var url = "http://beta.json-generator.com/api/json/get/NJqfdNMx-";
xmlhttp.onreadystatechange=function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var arr = JSON.parse(response);
var i;
var out = "<table>";
for(i = 0; i < arr.length; i++) {
out += "<tr><td>" +
arr[i].text +
"</td><td>" +
arr[i].text +
"</td><td>" +
arr[i].text +
"</td></tr>";
}
out += "</table>";
document.getElementById("id01").innerHTML = out;
}
}

Your JSON response contains object it doesn't directly contain array so you can't loop on response directly.
Your JSON response contains object with property text which contains further properties.
var arr = JSON.parse(response);
var text = arr.text;
This is value of text
{itemCount: 31, sleepActivities: Array[26], runActivities: Array[1], freePlayActivities: Array[3], bikeActivities: Array[1]}
Now you can loop on sleepActivities or runActivities or freePlayActivities or bikeActivities. You can loop over any array you want to get data.
for(i = 0; i < text.sleepActivities.length; i++) {
//your code
}

Need your Json data or Please go through this site
W3School JSON Handling Methods
which helps you more

Your response contains object but you don't need use JSON.parse. Because the response is pure JSON. You need to follow the below steps
var arr = response.text
it will return below result
Object {itemCount: 31, sleepActivities: Array[26], runActivities: Array[1], freePlayActivities: Array[3], bikeActivities: Array[1]}
for eg if you want to take sleepActivities from the response. Follow the process
var sleepActivities = response.text.sleepActivities
$.each(sleepActivities ,function(i,val){
console.log(val.heartRateSummary.averageHeartRate);
})

Related

how to reverse order of xml using javascript

i want to reverse the order of this list using javascript i have tried different ways that i knew about it is
the below file show straight i want to reverse it.i dont know xml node much and how to get it reverse it totally
<messages>
<messageset>
<name>torje</name>
<time>1533904431</time>
<message>Vvvhjhf</message>
</messageset>
<messageset>
<name>moneyman</name>
<time>1533904437</time>
<message>njkjlmkmkl</message>
</messageset>
<messageset>
<name>anjali</name>
<time>1533904445</time>
<message>A hi fyi bk MLS egg FG ch bhi CDG jk IC</message>
</messageset>
</messages>
it the present code this shows order wise table like torje - Vvvhjhf , moneyman - njkjlmkmkl, anjali - A hi fyi bk MLS egg FG ch bhi CDG jk IC this should be reverse first anjali's msg then moneyman then torje's (sorry for bad typing in message)
function fetch() {
setTimeout( function() {
loadDoc()
fetch();
}, 100);
}
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "../clubs/club.xml", true);
xhttp.send();
}
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>NAME</th><th>message</th></tr>";
var x = xmlDoc.getElementsByTagName("messageset");
for (i = 0; i < x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("message")[0].childNodes[0].nodeValue +
"</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}
Can create an array and push each data row into the array then Array#reverse() that array and convert back to string using Array#join()
function myFunction(xml) {
var rowsArray =[]
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>NAME</th><th>message</th></tr>";
var x = xmlDoc.getElementsByTagName("messageset");
for (i = 0; i < x.length; i++) {
// new variable `row`
var row = "<tr><td>" +
x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("message")[0].childNodes[0].nodeValue +
"</td></tr>";
// add row to array
rowsArray.push(row)
}
// reverse and return array to string
table += rowsArray.reverse().join('');
document.getElementById("demo").innerHTML = table;
}
Currently your for loop processes the messages in standard order.
for (i = 0; i < x.length; i++) {
You could just reverse this loop:
for (i = x.length - 1; i >= 0; i—-) {

How to get json array from json file?

im creating Image Hotspot using javascript, i need to get a data (x,y and Info) from json file, currently im getting data from Javascript Array. How can i get it from json file?
Code Pasted here;
var points;
var l_nOldX;
var l_nOldY;
function createHotspots(){
var points = new Array(
/*Tamilnadu*/
[38.7, 85.6, "0168"],
[36.1, 85.3, "1843"],
[38.5, 88.3, "39647"],
[34.8, 29.2, "12320"]
);
var divHotspot = document.getElementById("loadImages");
for(pi = 0; pi < points.length; pi++){
var hs = document.createElement("div");
hs.className = "hotspot";
hs.style.position = "absolute";
hs.style.left = "calc(" + points[pi][0] + "% - 8px)";
hs.style.top = "calc(" + points[pi][1] + "% - 0px)";
hs.style.width = "15px";
hs.style.height = "15px";
var html;
if (points[pi][0] < 31) {
html = "<table cellpadding='0' cellspacing='0' class='tbltooltipright' align='center'><tr><td id='img9' align='center'><div align='center'><div class='divtooltip'><div class='divclose'></div>" + points[pi][2] + "</div><div id='triangle-down' class='arrow_boxr'></div></td></tr><tr><td align='center' id='img10' ></td></tr></table>";
// alert('a');
hs.innerHTML = html;
$(hs).bind("mouseenter", function () {
$(".tbltooltipnormal").hide();
$(".tbltooltipleft").hide();
$(".tbltooltipright").hide();
$(this).find(".tbltooltipright").show();
});
}
else {
html = "<table cellpadding='0' cellspacing='0' class='tbltooltipnormal' align='center'><tr><td id='img9' align='center'><div align='center'><div class='divtooltip'><div class='divclose'></div>" + points[pi][2] + "</div><div id='triangle-down' class='arrow_boxn'></div></td></tr><tr><td align='center' id='img10' ></td></tr></table>";
hs.innerHTML = html;
$(hs).bind("mouseenter", function () {
$(".tbltooltipnormal").hide();
$(".tbltooltipleft").hide();
$(".tbltooltipright").hide();
$(this).find(".tbltooltipnormal").show();
});
}
$('.divclose').on('click touchstart', function () {
//debugger;
$('.tbltooltipnormal').hide();
$('.tbltooltipleft').hide();
$('.tbltooltipright').hide();
return false;
});
divHotspot.appendChild(hs);
}
}
In above code i've get data from "Points" array instead of i need to get this array data from one json file ?
Please help me to get this fixed.
thanks in Advance.
You can use ajax to get the data from the json file and just wrap the existing code in a function which takes an argument and just assign that argument to the desired var:
var points;
var l_nOldX;
var l_nOldY;
function createHotspots(points){ // <---pass the array
var points = points; // assign it here
var divHotspot = document.getElementById("loadImages");
...
}
$.ajax({
url:'points.json', //<----call the json file
type:'GET',
dataType:'json',
success:createHotspots // reference to the data
});
var yourJsonDataFromFile=undefined;
var getJsonData=function () {
console.log("fetching data from JSON file");
var url = "path_to_your_json _file";
var ajaxHttp = new XMLHttpRequest();
ajaxHttp.overrideMimeType("application/json");
ajaxHttp.open("GET",url,true);
ajaxHttp.setRequestHeader("Access-Control-Allow-Origin", "*");
ajaxHttp.send(null);
ajaxHttp.onreadystatechange = function () {
if(ajaxHttp.readyState == 4 && ajaxHttp.status == "200")
{
yourJsonDataFromFile = JSON.parse(ajaxHttp.response);
}
};
}
modify this code add file path in path_to_your_json _fileand call this function getJsonData() after that your data will be in yourJsonDataFromFile in json format , hope this will resolve your issue
Please try this. Should solve your problem
$.getJSON('<path_to_your_json_file>/file.json', function(data) {
var points = data;
});

How to fetch image through json using jquery or JS in HTML

Can any body help, m totally new in Json I want to fetch the image but m bit confuse in the array and object thing. Or is it possible to fetch image without img tag. Thank you in advance
This is my JSON link
this what I have tried:
function myFunction(worldpopulation) {
var out = "";
var i;
for(i = 0; i<worldpopulation.length; i++)
out += '' + worldpopulation[i].rank;
document.getElementById("id01").innerHTML = out;
}
just help me to fetch "rank" only
{ "worldpopulation":
[
{
"rank":1,"country":"China",
"population":"1,354,040,000",
"flag":"http://www.androidbegin.com/tutorial/flag/china.png"
},
{
"rank":2,"country":"India",
"population":"1,210,193,422",
"flag":"http://www.androidbegin.com/tutorial/flag/india.png"
},
{
"rank":3,"country":"United States",
"population":"315,761,000",
"flag":"http://www.androidbegin.com/tutorial/flag/unitedstates.png"
},
]
}
The first thing you will get the content of your json content from this page using XMLHttpRequest
var request = new XMLHttpRequest();
var url = "http://www.androidbegin.com/tutorial/jsonparsetutorial.txt";
request.onreadystatechange = function() {
if(request.readyState == && request.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
myFunction(myArr);
}
}
the implementation of myFunction
function myFunction(myArr)
{
for(var i=0; i< myArr.length; ++i) {
var img ; // get your element you want to place img inside
img.src = myArr[0].flag;
}
}
you can use .filter() to get image array.
var imageArr = [];
imageArr = worldpopulation.filter(function(val,indx){
return val.flag;
});
you can use jquery in following way
$.getJSON( "http://www.androidbegin.com/tutorial/jsonparsetutorial.txt",function( data ) {
$.each( data.worldpopulation, function( key, country) {
console.log('Image Url',country.flag)
});
});

how to check whether NAN is present in json string or not

suppose i have below function, which is getting jsonData in the form of jason, i validate the var jsonData to check for NaN ?
function save() {
var jsonData = getEnteredValue();
$.ajax({
type : 'POST',
url : 'saveSalesForecast.json',
data : 'jsonPostData=' + jsonData,
success : function() { //alert("success");
}
});
}
i only know how to replace NAN but don know how to check for NAN!
jsonData = JSON.parse(jsonData.replace(/\bNaN\b/g, "null"));
here is remaining function:(any field values can be string,numbers but it should not be NAN
function getEnteredValue() {
var rowIds = $("#salesForecastGrid").jqGrid('getDataIDs');
var ids=[];
var jsonPostData = "[";
for ( var i = 0; i <= rowIds.length-1; i++) {
$("#salesForecastGrid").jqGrid('editCell', i, 2, false);
var forecastedSales = parseFloat($("#salesForecastGrid")
.jqGrid('getCell', rowIds[i], 'forecastedSales'));
if (!((forecastedSales == "") || isNaN(forecastedSales) || (forecastedSales ==0))) {
if (ids.indexOf(rowIds[i])==-1){
ids.push(rowIds[i]);
}
}
}
for ( var i = 0; i <= ids.length-1; i++) {
var forecastedSales = parseFloat($("#salesForecastGrid")
.jqGrid('getCell', ids[i], 'forecastedSales'));
var id = $("#salesForecastGrid").jqGrid('getCell', ids[i],
'id');
var date = $("#salesForecastGrid").jqGrid('getCell',
ids[i], 'day');
if (id < 0) {
id = 0;
}
var record = "{" + "id:" + id + "," + "date:" + date + ","
+ "forecastedSales:" + forecastedSales + "}";
jsonPostData = jsonPostData + record;
if (i != ids.length) {
jsonPostData = jsonPostData + ",";
}
}
jsonPostData += "]";
return jsonPostData;
}
Json Data like:
"[{id:68447,date:04-17-2014,forecastedSales:8420.42},{id:68448,date:04-18-2014,‌​forecastedSales:9912.68},]"
Your problem is that you are creating the JSON manually, and thus end up with invalid JSON. Do yourself a favor and use JSON.stringify:
function getEnteredValue() {
var rowIds = $("#salesForecastGrid").jqGrid('getDataIDs');
var ids=[];
var data = [];
// ...
for ( var i = 0; i < ids.length; i++) {
// ...
data.push(
{id: id, date: date, forecastedSales: forecastedSales}
);
}
return JSON.stringify(data);
}
Since NaN is not a valid value in JSON, it will automatically be converted to null. Example:
> JSON.stringify({a: NaN});
"{"a":null}"
For more info see Using native JSON.
NaN is not acceptable in JSON. JSON specification does not support NaN as a value. Even when javascript object has NaN value, it will be converted to null when you serialise to JSON format.
First of all, JSON is not an Javascript Object. JSON is general format which can be understand by all languages.

How to parse XML string with Prototype?

I have a string <ul><li e="100" n="50">Foo</li><li e="200" n="150">Bar</li></ul> and on client side I have to convert it to JSON. Something like {data:['Foo','Bar'],params:['100;50','200;150']}
I found a pretty good way to achieve it in here so my code should be something like that
var $input = $(input);
var data = "data:[";
var params = "params:[";
var first = true;
$input.find("li").each(function() {
if (!first) {
data += ",";
params += ",";
} else {
first = false;
}
data += "'" + $(this).text() + "'";
var e = $(this).attr("e");
var n = $(this).attr("n");
params += "'" + e + ';' + n + "'";
});
return "{data + "]," + params + "]}";
But the problem is that I can't use jquery. How can I do the same thing with prototype?
You want to use a DOM parser:
https://developer.mozilla.org/en/DOMParser
Something like this...
var xmlStr = '<ul><li e="100" n="50">Foo</li><li e="200" n="150">Bar</li></ul>';
var parser = new DOMParser();
var doc = parser.parseFromString(xmlStr, "application/xml");
var rootElement = doc.documentElement;
var children = rootElement.childNodes;
var jsonObj = {
data: [],
params: []
};
for (var i = 0; i < children.length; i++) {
// I realize this is not how your implementation is, but this should give
// you an idea of how to work on the DOM element
jsonObj.data.push( children[i].getAttribute('e') );
jsonObj.params.push( children[i].getAttribute('n') );
}
return jsonObj.toJSON();
Also, don't manually build your JSON string. Populate an object, then JSON-encode it.
Edit: Note that you need to test for DOMParser before you can use it. Check here for how you can do that. Sorry for the W3Schools link.
Why you are building an array object with string? Why not
var data = new Array();
var params = new Array();
$$("li").each(function() {
data.push ($(this).text());
params.psuh($(this).attr("e") + ";" + $(this).attr("n"));
});
return {data:data.toString(), params:params.toString()};
or
return {data:data, params:params};

Categories