Loop through JSON object List - javascript

I am returning a List<> from a webservice as a List of JSON objects. I am trying to use a for loop to iterate through the list and grab the values out of the properties. This is a sample of the returning JSON:
{"d":[{"__type":"FluentWeb.DTO.EmployeeOrder",
"EmployeeName":"Janet Leverling",
"EmployeeTitle":"Sales Representative",
"RequiredDate":"\/Date(839224800000)\/",
"OrderedProducts":null}]}
So I am trying to extract the contents using something like this:
function PrintResults(result) {
for (var i = 0; i < result.length; i++) {
alert(result.employeename);
}
How should this be done?

Be careful, d is the list.
for (var i = 0; i < result.d.length; i++) {
alert(result.d[i].employeename);
}

had same problem today, Your topic helped me so here goes solution ;)
alert(result.d[0].EmployeeTitle);

It's close! Try this:
for (var prop in result) {
if (result.hasOwnProperty(prop)) {
alert(result[prop]);
}
}
Update:
If your result is truly is an array of one object, then you might have to do this:
for (var prop in result[0]) {
if (result[0].hasOwnProperty(prop)) {
alert(result[0][prop]);
}
}
Or if you want to loop through each result in the array if there are more, try:
for (var i = 0; i < results.length; i++) {
for (var prop in result[i]) {
if (result[i].hasOwnProperty(prop)) {
alert(result[i][prop]);
}
}
}

Here it is:
success:
function(data) {
$.each(data, function(i, item){
alert("Mine is " + i + "|" + item.title + "|" + item.key);
});
}
Sample JSON text:
{"title": "camp crowhouse",
"key": "agtnZW90YWdkZXYyMXIKCxIEUG9zdBgUDA"}

Since you are using jQuery, you might as well use the each method... Also, it seems like everything is a value of the property 'd' in this JS Object [Notation].
$.each(result.d,function(i) {
// In case there are several values in the array 'd'
$.each(this,function(j) {
// Apparently doesn't work...
alert(this.EmployeeName);
// What about this?
alert(result.d[i][j]['EmployeeName']);
// Or this?
alert(result.d[i][j].EmployeeName);
});
});
That should work. if not, then maybe you can give us a longer example of the JSON.
Edit: If none of this stuff works then I'm starting to think there might be something wrong with the syntax of your JSON.

var d = $.parseJSON(result.d);
for(var i =0;i<d.length;i++){
alert(d[i].EmployeeName);
}

This will work!
$(document).ready(function ()
{
$.ajax(
{
type: 'POST',
url: "/Home/MethodName",
success: function (data) {
//data is the string that the method returns in a json format, but in string
var jsonData = JSON.parse(data); //This converts the string to json
for (var i = 0; i < jsonData.length; i++) //The json object has lenght
{
var object = jsonData[i]; //You are in the current object
$('#olListId').append('<li class="someclass>' + object.Atributte + '</li>'); //now you access the property.
}
/* JSON EXAMPLE
[{ "Atributte": "value" },
{ "Atributte": "value" },
{ "Atributte": "value" }]
*/
}
});
});
The main thing about this is using the property exactly the same as the attribute of the JSON key-value pair.

I have the following call:
$('#select_box_id').change(function() {
var action = $('#my_form').attr('action');
$.get(action,{},function(response){
$.each(response.result,function(i) {
alert("key is: " + i + ", val is: " + response.result[i]);
});
}, 'json');
});
The structure coming back from the server look like:
{"result":{"1":"waterskiing","2":"canoeing","18":"windsurfing"}}

Related

Determine the last element of JSON object

My server(PHP) response JSON object like this data:
{
"0": {
"action_id": "80",
"action_transaction_id": "5743",
"action_matched_email": "test_1#gmail.com",
"action_by_user": "user1",
"action_count": "0",
"action_date": "2017-07-19 15:01:26"
},
"1": {
"action_id": "1",
"action_transaction_id": "1",
"action_matched_email": "Admin#email.com",
"action_by_user": "ADMIN",
"action_count": "4",
"action_date": "2017-07-19 15:10:08"
},
"new_count": {
"action_count": "4"
}
}
The data are not limited, sometimes server throws many data. It depends on what the condition is.
This is my ajax did after success:
success: function(data, status, jqXHR) {
$.each(data, function(i, row) {
document.getElementById("hidden_counter").value = "";//new_count value here
var allRows =window.parent.document.getElementsByClassName('row'+row.action_transaction_id+'');
for (var i = 0; i < allRows.length; i++) {
allRows[i].style.backgroundColor = '#008e00';
allRows[i].style.color = '#f0fff0';
//should exclude the last array when updating the bgcolor and style color of the row
}
});
}
I have 2 things to know and do.
How can I get the last object?
"new_count": {
"action_count": "4"
}
so that I can update my hidden input value to it.
How can I exclude the last object when updating the styles of rows?
You shouldn't mixup pure js with jquery:
success: function(data, status, jqXHR) {
$('#hidden_counter').val(data.new_count.action_count);
$.each(data, function(i, row) {
if (row.action_transaction_id === undefined) {
return;
}
$('.row' + row.action_transaction_id).css({
backgroundColor: '#008e00',
color: '#f0fff0'
});
});
}
If your object name is lets say jsondata then for accesing new_count you can get it using,
jsondata.new_count
If you want to access last element then you can access it through ,
jsondata.new_count.action_count
How can I get the last object?
Object keys are not sorted and are retrieved in an order specific to browsers. So you can try to do is, get list of keys and take the maximum value.
As commented before, this should do the trick:
var lastIndex = Math.max.apply(null, Object.keys(object).map(Number))
How can I exclude the last object when updating the styles of rows?
You can either stop loop at length - 1
or you can try to use CSS selectors:
var selector = '.row' + row.action_transaction_id + ':not(:last-child)';
var allRows = window.parent.document.querySelectorAll(selector);
// OR since you are using jQuery
var allRows = $(window).parent().find(selector)
// OR
var selector = '.row' + row.action_transaction_id;
var allRows = $(window).parent().find(selector).not(':last-child')
You can use Object.keys
success: function(data, status, jqXHR) {
var lastKey = Object.keys(data)[Object.keys(data).length-1];
$.each(data, function(i, row) {
if (i== lastKey) { /* It's the last key */ }
...
Note that for older browsers you may need to use the polyfill included in that link.
try this:
$.each(data, function(i, row) {
if(row["action_count"])
{
document.getElementById("hidden_counter").value = row["action_count"];
}
else
{
var allRows =window.parent.document.getElementsByClassName('row'+row.action_transaction_id+'');
for (var i = 0; i < allRows.length; i++) {
allRows[i].style.backgroundColor = '#008e00';
allRows[i].style.color = '#f0fff0';
}
}
});
first piece: get the element with greatest index (=length - 1)
second: loop all elements from index 0 until index < length-1
var lastArrayElement = allRows[allRows.length - 1];
var action_count = lastArrayElement.action_count;
// loop all but last element:
for(var i=0; i<allRows.length-1;i++){
do_something(allRows[i]); //custom function
}
assumption:
the index is correct and not resorted in the process of creating json object
the index is indeed a range from 0 to some integer, without values left out
edit
indeed the allRows.length will not work as it is an object (containing pure numeric values as properties).
Object.keys(allRows).length will give you the count van properties. However it will give you 3 as the last textual index is taken in the count as well.
var max = 0;
for(i = 0; i < Object.keys(allRows).length;i++) {
if(parseInt(Object.keys(allRows)[i]) > max) {
max = Object.keys(allRows)[i];
}
}
the last element then will be in
var lastArrayElement = allRows[max];

Get JSON data after it's stored in a variable

After getting JSON back from the ajax call, the data "response" is stored in the "theObj" variable; however, when I try to log "theObj" to the console, it results in multiple "[Object object]", even with JSON.stringify().
If I do a "theObj[0]" (response.results[0] works fine), I get "[", for the first character in "[Object object]".
Q: How can I store JSON in a variable and get the data back out afterward?
$.ajax(settings).done(function(response) {
for (var i = 0; i < 19; i++) {
//creating JSONenter[enter image description here][1]
theObj += response.results[i];
if (i == 18) {
//console.log(theObj.id)
console.log(JSON.stringify(theObj[0].id))
}
}
}
I think the error is in the line
theObj += response.results[i];
So try this instead
function (response) {
var list = response.results;
// if there is no reason for having 19, replace this with var end = list.length
var end = Math.min(list.length, 19);
for(var index = 0; index < end; index++) {
theObj.push(list[index]);
}
console.log(theObj);
}
We don't see the initialization of theObj variable
If it is an array you should use the push function to add elements to it
If it is a common object then use theObj[id] = list[index];
DISCOURAGED If it is a string then you should use theObj += JSON.stringify(response.results[i];) + ", ";, then make sure that you add } or ] at the end if it is an object or array respectively (and that it has also has { or [ in the begining) and then use JSON.parse(theObj) to convert it back to an object
Please let me know which of the above are you using
try this
$.ajax(settings).done(function(response) {
$.each( response, function( key, val ) {
console.log(val.id)
});
}
I assumed you want to get the data as object and not a string.
For that you have to use var object = JSON.parse(yourJSONString). This method returns an object based on your JSON string.
Example:
JSON result:
{
"name":"John Doe"
}
Javascript code:
var john = JSON.parse(result);
console.log(john.name); //prints John Doe

Passing string element to data key

I have a function that checks for a div, and if it exists it fills it with the matching data from a JSON array. The Div and the data have the same id & key, so I want to be able to put those in a string for a more elegant solution. However, the final element of trying to apply the string element to the data key doesn't seem to be working. I get "Cannot read property '0' of undefined"
Original code:
$.getJSON('myDataUrl', function(data) {
if ($("#title").length){document.getElementById("title").innerHTML=data.title};
if ($("#noun").length){document.getElementById("noun").innerHTML=data.noun};
if ($("#_id").length){document.getElementById("_id").innerHTML=data._id};
if ($("#owner_id").length){document.getElementById("owner_id").innerHTML=data.owner_id};
});
The more 'elegant' solution I'm trying to reach:
$.getJSON('myDataUrl', function(data) {
var contentString = "name,noun,_id,owner_id";
var splitContent;
splitContent = contentString.split(",");
for(i = 0; i < splitContent.length; i++)
{if ($("#" + splitContent[i]).length){
document.getElementById(splitContent[i]).innerHTML=data.splitContent[i];
};
}
Looks like should be enough:
$.getJSON('myDataUrl', function (data) {
for (var k in data) {
$("#" + k).html(data[k]);
}
});
The problem is data.splitContent[i]. That should be data[splitContent[i]]. That is, you want to use the current key (e.g. name) as a key in the data object.
You could also use jQuery's Map.
$.map(data, function(value, key) {
$("#" + key).html(value);
});
Here's the working JSBin : http://jsbin.com/tocege/2/edit?html,js,output

Read values from JSON object

I am currently trying to get contents from a JSON object.
I've been looking all over google and what I think should work, for some reason, does not.
The JSON looks something like this:
{"locatie0":{"naam0":["Domplein"],"value0":["value1"]},"locatie1":{"naam1":["Neude"],"value1":["value1"]},"locatie2":{"naam2":["Vredenburg"],"value2":["value1"]},"locatie3":{"naam3":["Stadhuisbrug"],"value3":["value1"]},"locatie4":{"naam4":["Korte Minrebroederstraat"],"value4":["value1"]}}
I use below code to read the file but for some reason it will always return undefined or NaN.
$.ajax({
url: "_data/pleinen.json",
type: 'get',
dataType: "json",
success: function(data) {
for(var k = 0; k < _loc.length; k += 1) {
var _locaties = data.locatie[k].naam[k];
// Should alert "Domplein", "Neude", "Vredenburg", "Stadhuisbrug", "Korte Minrebroekstraat",
alert(_locaties);
}
}
});
Can anybody see if i've made any mistakes in my code or if there's a better way to read the values?
locatie[k] tries to access the property k of the object in locatie, but in your case, the number is part of the name itself. You have to build the property name dynamically. In addition, each property of the nested objects is an array with one element, so you have to access the first element:
var _locaties = data['locatie' + k]['naam' + k][0];
Your data structure is a bit strange though. The numbers in the property names makes accessing the data more difficult. If you can change it, change it to an array of objects and don't use arrays for the properties if you don't need them:
[{"naam": "Domplein", "value": "value1"}, {"naam": "Neude", "value":"value1"}]
Then accessing the data is simply:
for (var i = 0, l = data.length; i < l; i++) {
var _locaties = data[i].naam;
}
A JSON does not guarantee any order like an array.
But in your case, the keys of the JSON have index hints, so try accessing "naam" with:
data["locatie" + k]["naam" + k]
Try this:
$.ajax({
url: "_data/pleinen.json",
type: 'get',
dataType: "json",
success: function(data) {
for(var k = 0; k < _loc.length; k += 1) {
var _locaties = data['locatie'+k]['naam'+k][0];
alert(_locaties);
}
}
});
As the value of naam property is array you need to fetch first item from it in order to get string value.
The locatie and the naam are not arrays, so you cannot access them like the way you do.
You have to combine the number with the name as a string. Something like that
data['locatie'+k]
try this ;
k = 0;
console.log(
data[ 'locatie'+ k]['naam'+ k][0],
data[ 'locatie'+ k]['value'+ k ][0]
);
k = 1;
console.log(
data[ 'locatie'+ k]['naam'+ k][0],
data[ 'locatie'+ k]['value'+ k ][0]
);

how can i print data of array?

Here are my codes:
app.get('/index/:name',function(req, res){
data = connection.query('SELECT * FROM deneme', function(err, rows, fields){
if(err) throw err;
veri = rows;
return veri;
});
console.log(data);
res.render('index', {
title: req.params.name,
para: data
});
});
When i call localhost:8080/index/example it returns [object Object]
I want to print data of array, how can i do this?
I can do it when I'm using php with print_r() function..
Meantime, array's data:
Id Name
1 yab
2 sad
I think OP just want to print the data for debugging purposes, for that you can use the following cross-browser way that uses JSON to print a nice representation of the data:
console.log( JSON.stringify(data, null, 4) );
Something like this should work:
for (var colName in data) {
console.log("column " + colName);
var rows = data[colName];
for (var i = 0; i < rows.length; i++) {
console.log(rows[i]);
}
}
You will have to tweak it for your needs, that's the general way to iterate such objects.
You need to iterate the result collection and print the attributes
$.each(resultArray, function() {
this.id;//use this to write id
this.name;//use this to write name
});
To output to the console you could do something like:
for(var index in data) {
var item = data[index];
var output = [];
for(var field in item) {
output.push(item[field]);
}
console.log(output.join("\t"));
}
For outputting in html, you'd do something like similar, but creating actual HTML nodes. Maybe, something like:
var output = ["<table>"];
for(var index in data) {
output.push("<tr>");
var item = data[index];
for(var field in item) {
output.push("<td>");
output.push(item[field]);
output.push("</td>");
}
output.push("</tr>");
console.log(output.join("\t"));
}
output.push("</table>");
element.innerHTML = output.join("");
I've not tried that in a browser, so there might be a couple of mistakes, but that should do it.
Let me know if you'd like any more help.

Categories