JavaScript/jQuery solution for looping through JSON objects - javascript

I have this kind of JSON sent from PHP:
{"status":"error","message":"Firstname is invalid"}{"status":"error","message":"Lastname is invalid"}{"status":"success","message":"Middle name is fine"}
Ajax is retrieving me that in the success thingy:
success:function(data){
data=JSON.parse(data);
//need to loop trough data here
}
so the problem is that I need to console.log(data.status /* AND */ data.message) at once.
(ignore the comment above)
So in the JSON example above I want to be able to console.log the following:
(1) error Firstname is invalid
(2) error Lastname is invalid
(3) success Middle name is fine
(the above numbers in "()" just means how it should look like in the console thingy in chrome. I don't need to have them actually numbered)
////////
What I am actually trying to accomplish is to display the success/error messages with alrtify.js based on status.value (wither success or error). I don't want to display them all in one notification. I want each of the error/success appear as separate notification. I need to loop through them for that.

Please have a look on your JSON format. It should be like :
[{"status":"error","message":"Firstname is invalid"},{"status":"error","message":"Lastname is invalid"},{"status":"success","message":"Middle name is fine"}];
So ultimately you will be able to loop.
var data = [{"status":"error","message":"Firstname is invalid"},
{"status":"error","message":"Lastname is invalid"},
{"status":"success","message":"Middle name is fine"}];
for(var i in data)
{
console.log(data[i].message)
}

Assuming that what you are actually receiving is an array rather than that invalid JSON that you've shown there:
success:function(data){
data=JSON.parse(data); // you probably shouldn't be using this line
data.forEach(function (item) {
console.log(item.status + ' ' + item.message);
});
}

This code works like a charm for me.
Plase pay attention, that in my string objects are divided by comma, instead of yours '{"status":"error","message":"Firstname is invalid"}{"status":"error","message":"Lastname is invalid"}{"status":"success","message":"Middle name is fine"}'
var data = '[{"status":"error","message":"Firstname is invalid"}, {"status":"error","message":"Lastname is invalid"}, {"status":"success","message":"Middle name is fine"}]';
var parsedData = JSON.parse(data);
parsedData.forEach(function(item, index) {
alert(item.status + " - " + item.message);
console.log(item.status + " - " + item.message);
});

success:function(data){
data=JSON.parse(data); // you probably shouldn't be using this line
var data = $.parseJSON(item);
for (var i=0; i < data.length; i++){
var obj = data[i];
var status = obj.status;
var message = obj.message;
}
});

Related

Am I building the JavaScript objects correctly for a JSON string array?

In JavaScript I have the following code:
for (i = 1; i<3; i++)
{
// above I collect check_a and check_b through radio button responses.
var connectJSON = ",";
var passObj = {id:i, ask:check_a, description:check_b};
// adding object string together in tempObj
var tempObj = tempObj + connectJSON + passObj;
}
// get ready for transport to server and display result of string
var data = JSON.stringify(tempObj);
console.info("info: " + data);
// post string to server
$.ajax
({
type: 'POST',
url: 'out.php',
data: {data: data},
success: function(msg)
{
alert(msg);
}
});
In out.php I try to determine the result back from the server. The code is as follows:
<?php
if (ISSET($_POST['data']))
{
echo "TRUE";
}
ELSE
{
echo "False";
}
var_dump($_POST['data']);
?>
I am getting this message, AJAX alert (msg) :
**True** string(42) ""question, [object Object], [object Object]""
Apparently this message is describing the string array being passed.
What I now need to do, if the format is correct, is to be able to access the string array - maybe with JSON_decode and identify properties of the array so that I can make insertions into a MySQL database.
Thanks for any AND all help...
var connectJSON = ",";
var passObj = {id:i, ask:check_a, description:check_b};
// adding object string together in tempObj
var tempObj = tempObj + connectJSON + passObj;
First of all. If you just test this part in the console you will see that if you concatenate JS object and the string ',' you get the string "[object Object],[object Object]". You need to first stringify the JS object before concatenating it with strings.
Second I can really seem to understand your code but looping that code will just override those variables because they are declared in the loop so that doesn't seem correct. Probably you want to get the declarations out of the loop.
Otherwise it's kind of like this - you stringify the Js object and pass it as data to the ajax.
No. To build JSON, first build a valid structure, then use JSON.stringify on the result; don't convert to string while building the structure. connectJSON + passObj will force passObj to string, resulting in "[object Object]".
Instead:
var array = []; // <== An empty array
for (i = 1; i<3; i++)
{
// Push entries into the array
array.push({id:i, ask:check_a, description:check_b});
}
// Convert to JSON
var data = JSON.stringify(array);
Side note: The code in your question didn't declare i anywhere. If your real code doesn't, it's falling prey to The Horror of Implicit Globals.* Be sure to declare your variables. :-)
* (that's a post on my anemic little blog)
The issue is here var tempObj = tempObj + connectJSON + passObj;. You are concatinating objects and strings. In that case JavaScript will use Object.prototype.toString() first and then do the concatination. and Object.prototype.toString() in case of objects will produce [object Object]. To fix this you have to create an array like below.
var tempObj = [];
for (i = 1; i < 3; i++) {
// above I collect check_a and check_b through radio button responses.
var connectJSON = ",";
var passObj = {
id: i,
ask: check_a,
description: check_b
};
tempObj.push(passObj);
}
Also, you can skip JSON.stringify() and directly submit the JS object.
I'm trying to understand how is this deceleration :
var tempObj = tempObj + etc...;
possible ?
you cant set the value of something you just declared,
to the same thing you just declared .

Is it possible to use a string to reference a json object within an Ajax statement?

So i have a javascript function. It performs one ajax call, to retrieve a json object full of data. Within the success function of that ajax call i perfrom ANOTHER ajax call to retrieve the names of the columns of data for that particular set. (yes i'm sure there's a better way but thats not my issue). At this point in time i have two variables: items(json array) and interfaceCols(just an array of strings). Then i try to create an html string to create a table with said data.
Here is my code which will make everything more clear:
$.ajax({
url:"/ryan/nonEmber/ajax.php?table=Interfaces",
beforeSend: function(XMLHttpRequest){},
success: function(data, textStatus) {
interfaceCols = data.split(" ");
$.getJSON("/ryan/nonEmber/getJson.php?table=Interfaces", function( data ){
var items = [];
$.each(data.post, function(key, val){
items.push(val);
});
for(i = 0; i < items.length; i++){
var myString = '<tr id = "visibleRow">';
console.log(items[i].interfaceCols[4]);
for(j = 0; j < interfaceCols.length; j++){
myString = myString + '<td id = "visibleDef">' + items[i].interfaceCols[j] +'</td>';
}
myString = myString + '</tr>';
interfaces.push(myString);
}
});
}
});
My javascript file throws an error on the "myString = myString + '<td id ='... line.
I am almost positive that it is because i'm just placing a string at the end of "items[i]" with ".interfaceCols[j]"
Can anybody suggest a way to do this? The whole point is so that i dont have to manually type out every column name, because i have alot of tables and each table has many columns.
Given a JS object s:
s = {a: 1, b: 2}
You have (at least) two options to access an attribute:
s.a // returns 1
Which seems to be what you are trying to do right now. To access it with a dynamic name, you can use:
s['a'] // returns 1
In your case, it should be:
items[i][interfaceCols[4]]

Dictionary in JavaScript

Currently I tried to reform my JSON data to a dictionary to store only needed data in an array with key and value.
* Edit to put my full code. *
This is how I do:
var myData = [];
var urlPath = "https://tipjira.pgdev.abcd.com/rest/api/2/search?jql=project=GRIFR14%2Band%2BfixVersion=15018";
var jiraMapping = [];
$.ajax({
url : "http://frparwself22.dhcp.par.abcd.com:8080/jiraproxy/jira?url=" + urlPath,
dataType : 'json',
type: 'GET',
success : function(data) {
for (var i=0; i<data.issues.length; i++) {
var obj = {};
obj[data.issues[i].key] = data.issues[i].self;
jiraMapping.push(obj);
alert(jiraMapping.length);
}
},
error : function() {
alert("Error!")
}
});
alert(jiraMapping.length);
My original data is {issues:[{...,"self":"/rest/api/2/issue/175074","key":"GRIFR14-36",...}, {...,"self":"/rest/api/2/issue/175075","key":"GRIFR14-37",...}, ...]}. And I want to reform to have the array with key and value which are key and self.
So the data in my jiraMapping should be something like [{k1:v1}, {k2,v2}, ...].
But when I tired to print the length of jiraMapping, the length is 0.
I tried to put alert to check key and value that I add to the array and the values exist.
I don't know where is the problem exactly. Please help...
Without knowing exactly what information you're passing in, it's hard to say what's going wrong. That being said, my first guess is that data/myData isn't formatted the way you think. For instance, if myData.issues.length is 0, nothing in the loop will get executed.
There's also a chance that you're never actually running the success function. Could you post some more code?
The problem lies in the data that you are receiving or you have a typo somewhere later when checking length. This all looks fine, and I tried to replicate your problem like this:
var jiraMapping = [];
var myData = [{"A":"a"},{"B":"b"}];
for (var i=0; i<myData.length; i++) {
var obj = {};
obj[myData[i]] = myData[i];
jiraMapping.push(obj);
}
console.log(jiraMapping);
but this works fine, fiddle here: http://jsfiddle.net/GWpBs/2/

JavaScript & jQuery parse JSON in loop

Sorry about asking this, I can't get it to work even with looking at other questions...
I have a JSON output in "json.php", for example:
[
{"serverid":"1","servername":"Server One"},
{"serverid":"2","servername":"Server Two"}
]
I have a script, to grab the data & parse it into a variable
var servers;
jQuery.get('json.php', function(data) {
servers = JSON.parse(data);
jQuery('#servers').servers.servername
});
I have a div to output the results to:
<div id="servers"></div>
Whatever I try, I always get some kind of
"Uncaught TypeError: Cannot read property 'servername' of undefined" error.
I'd also like to look around the results, however I can't even get it to print atm.
Again sorry for another question like this
Don't you mean something like this? the jQuery object (which is a reference to your div) knows nothing about servername. Also, you'll need to iterate through the array of items in order to get them all:
servers = $.parseJSON(data);
$.each(servers, function(index, value) {
$("#servers").text($("#servers").text() + " " + value.servername);
});
Fiddle: http://jsfiddle.net/H2RC2/1/
The error message is all you need.
The jQuery('#servers') wrap the #servers div in the jQuery object. And this object has got no property such as servers.
Rather you could use:
var servers = JSON.parse(data);
var res = '';
for(var i = 0; i<servers.length; i++){
res = res + '<p>' + servers[i].servername +'</p>';
}
$('#servers').append(res);

How to convert a json formatted string into a json array in javascript

I am using the $.post() method to retrieve a json formatted string which looks like this:
{elementid:10},{elementid:11},{elementid:12},{elementid:14},{elementid:15}
In the success callback function of $.post(), I would like to loop the values of this json formatted string but I can't figure out how to do it.
// data returns {elementid:10},{elementid:11},{elementid:12},{elementid:14}, etc.
$.post('form.php',
{'postvalues' : input_ids},
function(data){
var elements = Array();
elements = [data];
for(var i=0; i<elements.length; i++) {
var value = elements[i]['elementid'];
alert('value = '+value);
}
});
When I do this, instead of getting value = 10, value = 11, value = 12, etc. in the alert box,
I get value = undefined
What must I change in the format of the variable 'data' so that it will be interpreted as array values and not a string?
thanks for your help
Your string isn't valid JSON if you don't have the '[' and ']' characters.
You can add those in , then parse it using the jQuery.parseJSON()[docs] method.
elements = jQuery.parseJSON( '[' + data + ']' );
...but it would be better if you sent correct JSON data from the server.
Also, your JSON keys must be wrapped in double quotes.
{"elementid":10},{"elementid":11},{"elementid":12},{"elementid":14},{"elementid":15}
Your query isn't returning valid JSON. It should be [{"elementid":10},{"elementid":11},{"elementid":12},{"elementid":14},{"elementid":15}] and not {elementid:10},{elementid:11},{elementid:12},{elementid:14},{elementid:15}. Is there any way you can fix that? Otherwise, you will have to do this:
elements = jQuery.parseJSON("[" + data + "]");
The right thing to do, however, is to return valid JSON from the server (if you have any control over that).
use JSON.parse(data) to put a string which contains a JSON object in a variable
Try this, it looks like you are getting passed an array (apart from the missing surrounding []), and if you tell jquery that it's json it'll parse it for you properly:
$.post('form.php', {'postvalues' : input_ids}, function(data){
for(var i=0; i<data.length; i++) {
var value = data[i]['elementid'];
alert('value = '+value);
}
}, 'json'); // telling it that the content received is json
Use the "for in" statement. Such as:
for (var x in data) {
console.log(data[x]['elementid']);
}
I tested it and it perfectly worked!
Hope this helps.
Ps. Console.log() output the result in the browser console (so it won't work in IE, of course).

Categories