Json data- key values, Object.Keys error - javascript

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.

Related

NodeJS not able to process array of objects received via POST

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)

Trying to store json data into an javascript array

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;

Accessing JSON parsed object

So here is my JS code:
$(document).ready(function() {
$.ajax({
url: "/",
type:"POST",
beforeSend: function (xhr) {
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
success:function(data){
console.log(data);
},error:function(){
console.log("error!!!!");
}
});
});
And this is what I get in my console:
Object { all_creations: "[{"id":"2","user_id":"2","title":"D…" }
But now I'd like to do something like:
console.log(data.user_id)
But this return nothing..
Same for:
console.log(data['all_creations'].user_id)
console.log(data['all_creations'][0].user_id)
console.log(data[0].user_id)
...
I am using laravel5 btw and this JSON object is return by the toJson() function. (if this is any help)
I know this question has already been answered millions times but for some reason I cannot get it work on my project... I am not a pro in Javascript or anything related to it like JSON. Ajax, JSON remain for me a source of intense pain. I hope to get it one day... seriously ^^
If anything, this is a rough guide to how you can access your data:
Object { all_creations: "[{"id":"2","user_id":"2","title":"D…" }
^^^^^^^^ ^
The marked areas indicate that data is a standard object, so it has already been parsed.
Object { all_creations: "[{"id":"2","user_id":"2","title":"D…" }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The inner portion says that data.all_creations is a property that contains a string value.
Object { all_creations: "[{"id":"2","user_id":"2","title":"D…" }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The string value itself seems to contain a JSON encoded value, so you would need to parse that first:
var creations = JSON.parse(data.all_creations);
Then, from the string value you can see it contains an array with an object as the first element.
alert(creations[0].user_id) // 2
I feel like your best bet here would be to test it in Chrome and use the F12 developer tools to see what is coming back from the server. Maybe check the request in the Network tab or try to figure out the proper way to retrieve the user_id in the console.
If confused take a look at some F12 Chrome developer tools tutorials.

Transforming a json format variable into a javascript array

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
}
});

Is there a standard way to serialize JSON using JavaScript and JQuery?

I've been looking through Stackoverflow for answers and there seems to be more than one way of serializing (converting the JSON response back into HTML and/or other code so we may do something useful with it).
The way I am using is this..
$.getJSON(
"https://www.googleapis.com/shopping/search/v1/public/products?callback=?",
{
key: "unique key code",
country: "US",
q: "iphone",
alt: "json"
},
function(data)
{
$.each(data.items, function(i, item)
{
//Do something with each object
}
}
So I'm using the $.getJSON method to retrieve the JSON response then looping through each object and doing something.
Is this way fine? Should I be using another function to retrieve the JSON response?
Regards,
LS
if you set dataType to json jquery parses json for you
$.ajax({
dataType:"json",
...
success:function(data){
$.each(data.items, function(i, item)
{
//Do something with each object
}
}
});
No, you are doing it perfectly fine. jQuery handles the conversion of "string" to json data and back.
There are native implementations of converting to and from JSON within browsers, however it is important to note that older browsers do not support this out of the box. You should include the json2.js library to ensure JSON support.
var dataJson={"something":"special"};
var jsonString=JSON.stringify(dataJson);
var dataJsonAgain=JSON.parse(jsonString);
jQuery has an additional hack in how it parses JSON if there is no native implementation, without using eval, since eval is evil! It looks somewhat like this;
(new Function("return "+dataJson))()
simplest way would be to stick to jQuery and its parseJSON function that does the polyfill for you.

Categories