I have the following json data that looks like this...
What I am trying to do is store the temp numbers into a javascript array to display on a graph. This is my code that I was working on...
$.ajax({
type: 'GET',
url: "http://api.openweathermap.org/data/2.5/forecast?q=Redlands,us&mode=json&units=imperial&cnt=20&APPID=5eea63b2ee3505c58713d9149832d4c5",
dataType: 'json',
success: function(data){
//console.log(data.list[0].main.temp);
//trying to parse through data for graph
var date = [];
$.each(data,function(index, data){
date.append(data.list[index].main.temp);
});
}
});
But it is not working I get the following error...
Uncaught TypeError: Cannot read property 'city' of undefined
Anyone know how I can fix this?
i see working , same from Erik Engervall, i change var data for current
$.each(data.list,function(index, current){
date.push(current.main.temp);
});
It seems you're iterating over the entire data object, whereas I believe you only wish to iterate over the data.list:
$.each(data.list, function(index, val) {
date.push(val.main.temp);
});
Also, JavaScript arrays uses push.
Updated answer after Mikel.
You need to use JSON.parse().
var dataList = JSON.parse(data).list;
Related
I'm having this collection of objects which are inside a html text area:
{"name":"John", "lname":"Doe","company":"example company","email":"johndoe#example.com"},{"name":"Katie","lname":"Jake","company":"example company","email":"katie#example.com"},
...
...
...
Is there a way to send the whole collection to node js and iterate through it to get values of objects?
My AJAX code:
$.ajax({
type: "POST",
url: "https://example.com/nodeapp",
data: '['+document.getElementById("list").value+']',
success: function(data) {
console.log(data);
}
});
I tried to do a foreach on req.body, but it doesn't seem to work:
var arr = req.body;
arr.foreach(element=>{
console.log(element.email);
})
Gives the error:
TypeError: arr.foreach is not a function
At first , you have to parse the body by using JSON.parse() function .
Like this :
var arr = JSON.parse(req.body);
arr.forEach(element=>{
console.log(element.email);
});
The javascript's foreach also defined as arr.forEach(...) not arr.foreach(...) .
I found my problem! Incase someone is stuck with the same thing, the whole thing was a string:
'[{"name":"John", "lname":"Doe","company":"example company","email":"johndoe#example.com"},
{"name":"Katie","lname":"Jake","company":"example company","email":"katie#example.com"},
...
...]'
Which was considered as one property in JSON which has no value while the server received it. Pretty much like this:
{
"<<the array in string format>>" : ""
}
How I fixed this was, I pushed the objects separately into a new array and sent it to server with JSON content type. (Which was an actual array of objects)
I'm trying to retrieve the JSON data given below but I'm unable to.
Since I'm using Javascript Ajax success function, when I try doing alerts with the code,
$.ajax({
type:'GET',
url:myURL,
success : function(data) {
alert(data);
//{"object1":{"mainIsActive":"A","mainBuildingGL":"01493","mainIsUnderCons":"B"},"object2":[[{"statLabel":"Cafeteria","statCount":"1"},{"statLabel":"Restaurant","statCount":"2"}],[{"statLabel":"Cafeteria","statCount":"1"},{"statLabel":"Restaurant","statCount":"2"}],{"newBuildingGL":"15450"}]}
}
});
I am retrieving the below JSON data.
{"object1":{"mainIsActive":"A","mainBuildingGL":"01493","mainIsUnderCons":"B"},"object2":[[{"statLabel":"Cafeteria","statCount":"1"},{"statLabel":"Restaurant","statCount":"2"}],[{"statLabel":"Cafeteria","statCount":"1"},{"statLabel":"Restaurant","statCount":"2"}],{"newBuildingGL":"15450"}]}
But when I try trying to get the value of mainIsActive using:
alert(data.object1.mainIsActive);
I am getting the error in the console:
"Cannot read property 'mainIsActive' of undefined at Object.success (:143:30)"
Can you please help? I also attached the JSON image so you can understand the structure better.
The JSON data will be available in object structure once you have parsed it using
JSON.parse(StringYouWantToParse)
This code seems to work properly:
var x = '{"object1":{"mainIsActive":"A","mainBuildingGL":"01493","mainIsUnderCons":"B"},"object2":[[{"statLabel":"Cafeteria","statCount":"1"},{"statLabel":"Restaurant","statCount":"2"}],[{"statLabel":"Cafeteria","statCount":"1"},{"statLabel":"Restaurant","statCount":"2"}],{"newBuildingGL":"15450"}]}';
var data = JSON.parse(x);
alert(data.object1.mainIsActive);
I am trying to parse out all keys from a json data.
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
url: "History.aspx/GetFTEData",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
var returnedstring = data.d;
var colHeader = Object.keys(data[0]); <---- error line
}
});
});
</script>
However, var colHeader = Object.keys(data[0]); this doesn't work while running it with my IDE (VS2015) on my IE 11 or Firefox browser even though it works in the jsfiddle example:-
https://jsfiddle.net/qpu3cn5u/
The error message:- 0x800a138f - JavaScript runtime error: Object.keys: argument is not an Object
What alternatives do I have? such that I can only parse the keys out as column names for an html table that I am trying to populate with values.
example of data:-
var data = `[{"Customer Name":"XXXX","1999":76.000,"2000":68.000,"2001":49.000,"2002":41.000,"2003":47.000,"2004":56.000,"2005":33.000,"2006":51.000,"2007":56.000,"2008":52.000,"2009":55.000,"2010":52.000,"2011":57.000,"2012":55.000,"2013":93.000,"2014":92.000,"2015":62.000,"2016":71.833},{"Customer Name":"YYYYY","1999":29.000,"2000":27.000,"2001":35.000,"2002":37.000,"2003":32.000,"2004":29.000,"2005":44.000,"2006":49.000,"2007":69.000,"2008":109.000,"2009":108.000,"2010":150.000,"2011":189.000,"2012":215.000,"2013":53.000,"2014":78.000,"2015":65.000,"2016":63.000},{"Customer Name":"ZZZZ","1999":0.000,"2000":0.000,"2001":0.000,"2002":0.000,"2003":0.000,"2004":0.000,"2005":0.000,"2006":0.000,"2007":0.000,"2008":0.000,"2009":0.000,"2010":0.000,"2011":0.000,"2012":28.000,"2013":36.000,"2014":59.000,"2015":90.000,"2016":94.000},{"Customer Name":"AAAAA","1999":0.000,"2000":0.000,"2001":0.000,"2002":0.000,"2003":0.000,"2004":0.000,"2005":0.000,"2006":0.000,"2007":0.000,"2008":0.000,"2009":0.000,"2010":0.000,"2011":0.000,"2012":18.000,"2013":18.000,"2014":18.000,"2015":19.000,"2016":18.000}]`
It seems the problem is that the data[0] is still in its JSON state. This often happens when you encode individual objects, and then encode their enclosing array. The individual objects get double-encoded.
As a test, try this:
var parsed = JSON.parse(data[0]);
console.log(Object.keys(parsed));
If this shows the result that you wanted, then that tells you the double-encoding is the problem.
However, parsing it again is not the solution. You need to fix this on the server that's generating the JSON data so that it doesn't get double-encoded.
If you have to support older browsers you can always try and find examples of how to perform similar tasks using older styles/APIs. For example you can loop over JavaScrip object props by doing something like this:
for (var property in object) {
if (object.hasOwnProperty(property)) {
// do stuff
}
}
Similar question/code example found here.
However, Object.keys() is support is all major browsers. Including IE11, reference here.
I am using the Django framework to build a website.
In the Python file (views.py) I send to the Javascript function an array that has been transformed to json data
Python:
json_data=[1,2,3]
return HttpResponse(json.dumps(json_data), mimetype='application/json')
Then, in Javascript I display the json data in the html.
JavaScript:
function get_variable(){
$.get("/xhr_test/json/", function(json_data) {
$('.square').append('<p> ' + json_data + ' </p>');});
};
So far everything works. However, I would like to convert the "json_data", which I believe is a string, into an array.
I tried doing this:
function get_variable(){
$.get("/xhr_test/json/", function(json_data) {
var array = json_data.split(',');
$('.square').append('<p> ' + array[0]+ ' </p>');});
};
Unfortunately, this doesn't work.
Can someone please explain to me what could I do to convert the "json_data" variable into an array in JavaScript?
Thanks a lot.
When you send around data in JSON format it is a string (the main data), but a string formated in such a way that it's easy to recover the data with the original types (ie, your array). Javascript and jquery have different ways to do that. Using jQuery,getJSON is probably the most direct:
http://api.jquery.com/jQuery.getJSON/
You can use your browsers javascript console to see what exactly do your JS variables look like.
"this doesn't work" it's too vague...
Anyway, if I understood your problem, you are dealing with a string, not a JavaScript array... you have to evaluate the data returned from the ajax call:
var theJavaScriptArray = eval('(' + json_data + ')');
or better... use jQuery.ajax and specify json as dataType: jquery doc
In the end, thanks to Zah I discovered the "javascript console", which I didn't know it existed.
I could see that the error was that the "json_data" variable was not a string.
So this is the solution that worked for me:
function get_variable(){
$.get("/xhr_test/json/", function(json_data) {
var b=json_data.toString().split(',');
$('.square').append('<p> ' + b[0] + ' </p>');
});
};
There is a shorthand in jQuery to parse the json string automatically: jQuery.getJSON()
$.getJSON('/xhr_test/json/', function(data) {
console.log(data); // Here data is already a JavaScript object
});
This is basically the same as:
$.ajax({
url: "/xhr_test/json/",
dataType: "json",
success: function(data) {
console.log(data); // Here data is already a JavaScript object
}
});
Which again is about the same as:
$.ajax({
url: "/xhr_test/json/",
success: function(data) {
var json = $.parseJSON(data); // Here data is a string
console.log(data); // And json is JavaScript object
}
});
I'm using coldfusion and jquery. This is my first real go at jquery and I've searched and read for a long time without cracking this so any help would be greatly appreciated...
Ok, I have an autocomplete returning an id. I'm then passing the id to a second function that returns an array of datatype json. The autocomplete works great and I can get the json to display in an alert box but am a bit stuck on how to use the json results.
I'm trying to loop through the json array and write the values into radio buttons, which then dynamically display on page... So the whole idea is this.
user is selected from drop box and id is returned
user id from selection is passed to user options function and user options are returned in json arrary.
json array is looped through and on each iteration a radio button is created with appropriate values.
all radio buttons are then output to screen for access and selection.
The code I have so far is this :
<script type="text/javascript">
// <!--
$(document).ready(function() {
$("#userName").autocomplete({
cache:false,
source: "/jqueryui/com/autocomplete.cfc?method=getUser&returnformat=json",
//setup hidden fields
select:function(event,ui) {
var uid = ui.item.id;
$("#userid").val(ui.item.id);
// start call to get user options
$.ajax({
type: "POST",
url: "/jqueryui/com/autocomplete.cfc?method=getUserOptions&returnformat=json",
data: ({ userid: uid }),
success: function(data) {
alert(data)
}
});
/// end call to get user options
}
});
});
// --->
</script>
The json displayed in the "alert(data)" popup, which looks fine, is this :
[{"productname":"licence free","quantity":1,"term":12,"id":1},
{"productname":"licence basic","quantity":1,"term":24,"id":1},
{"productname":"licence full","quantity":1,"term":12,"id":2}]
I need to know how to loop through this data and create a radio button for each option, probably something like this, and display them all on screen, which I'm guessing I'll just write to a via the dom once I have something to write :
<input type="radio" name="userOption" value="#id#|#qty#|#term#">#productname#
I have tried a few things, without success, such as :
for(var i =0;i<Data.length-1;i++)
{
var item = Data[i];
alert(item.productname + item.id);
}
And
$.each(data.items, function(i,item){
alert(item);
if ( i == 3 ) return false;
});
I couldn't get either of these to work.
Anyway this is getting a bit long winded. Hope it's clear, and again any help or suggestions appreciated.
Thanks!
First check the datatype of the data parameter returned. You might first need to use .parseJSON() to construct a JSON object.
Then your for loop syntax is not correct. this code works for me:
var data = [{"productname":"licence free","quantity":1,"term":12,"id":1},
{"productname":"licence basic","quantity":1,"term":24,"id":1},
{"productname":"licence full","quantity":1,"term":12,"id":2}];
for (var i=0; i<data.length; i++) {
alert(data[i].productname);
}
Here's a jsfiddle
Try checking parseJSON jquery function.
I quess that the type is a string? If so try it with the javascript function eval. It converts a string to a javascript type.. in your case something like this should work:
Var new_data = eval(data);
Now it should be a workable array/object
Edit: to stay with the data variable:
data = eval(data);
Edit 2:
Your ajax call misses the dataType property:
dataType: "json"
With this you dont need the stuff above i said
Use a each loop to get data and appendTo function to print data in an HTML element with result1 id:
dataType:"json", //nature of returned data
success: function(data) {
var content = '';
$.each(data, function(i, dbdata) {
content += '<p>' + dbdata.columnName + '<p>';
});
$(content).appendTo("#result1");
}