JavaScript & jQuery parse JSON in loop - javascript

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

Related

Python CGI, FieldStorage and javascript array

I searched and searched, and I am certain there is a simple answer. However, the solution escapes me. I have javascript that takes all elements and puts the id attribute into an array, then sends it to an apache http server. Then, using python, the data is supposed to be retrieved, made into a python list, then iterated.
My problem is that I can't seem to get an iterable list. Here is the output from FieldStorage:
FieldStorage(None, None, [MiniFieldStorage('data', '[["NWS-IDP-PROD-KEEPALIVE-30678","NWS-IDP-PROD-2426831","NWS-IDP-PROD-2426829-2276816","NWS-IDP-PROD-2426827-2276815","NWS-IDP-PROD-2426823-2276812","NWS-IDP-PROD-2426824-2276814","NWS-IDP-PROD-2426823-2276811","NWS-IDP-PROD-2426823-2276813","NWS-IDP-PROD-2426822-2276809","NWS-IDP-PROD-2426822-2276810","NWS-IDP-PROD-2426822-2276808","NWS-IDP-PROD-2426822-2276807","NWS-IDP-PROD-2426821","NWS-IDP-PROD-2426819-2276806","NWS-IDP-PROD-2426818-2276805","NWS-IDP-PROD-2426817-2276804","NWS-IDP-PROD-2426815-2276801","NWS-IDP-PROD-2426816-2276803","NWS-IDP-PROD-2426813-2276800","NWS-IDP-PROD-2426807-2276797","NWS-IDP-PROD-2426806-2276796","NWS-IDP-PROD-2426805-2276795","NWS-IDP-PROD-2426803-2276793","NWS-IDP-PROD-2426802-2276792","NWS-IDP-PROD-2426800-2276791","NWS-IDP-PROD-2426796-2276787","NWS-IDP-PROD-2426797-2276789","NWS-IDP-PROD-2426793-2276785","NWS-IDP-PROD-2426792-2276784","NWS-IDP-PROD-2426787-2276779","NWS-IDP-PROD-2426791-2276783","NWS-IDP-PROD-2426783-2276775","NWS-IDP-PROD-2426785-2276777","NWS-IDP-PROD-2426784-2276776","NWS-IDP-PROD-2426789-2276781","NWS-IDP-PROD-2426788-2276780","NWS-IDP-PROD-2426786-2276778","NWS-IDP-PROD-2426790-2276782","NWS-IDP-PROD-2426781-2276773","NWS-IDP-PROD-2426779-2276771","NWS-IDP-PROD-2426778-2276770","NWS-IDP-PROD-2426777-2276769","NWS-IDP-PROD-2426774-2276766","NWS-IDP-PROD-2426768-2276762","NWS-IDP-PROD-2426764-2276760","NWS-IDP-PROD-2426758-2276751","NWS-IDP-PROD-2426757-2276750","NWS-IDP-PROD-2426756-2276749","NWS-IDP-PROD-2426754-2276747","NWS-IDP-PROD-2426755-2276748","NWS-IDP-PROD-2426753-2276746","NWS-IDP-PROD-2426752-2276745","NWS-IDP-PROD-2426750-2276743","NWS-IDP-PROD-2426749-2276742","NWS-IDP-PROD-2426748-2276741","NWS-IDP-PROD-2426747-2276740","NWS-IDP-PROD-2426743-2276736","NWS-IDP-PROD-2426744-2276737","NWS-IDP-PROD-2426746-2276739","NWS-IDP-PROD-2426745-2276738","NWS-IDP-PROD-2426538-2276561","NWS-IDP-PROD-2426539-2276562","NWS-IDP-PROD-2426536-2276559","NWS-IDP-PROD-2426535-2276558","NWS-IDP-PROD-2426502-2276526","NWS-IDP-PROD-2426501-2276525","NWS-IDP-PROD-2426495-2276519","NWS-IDP-PROD-2426490-2276514","NWS-IDP-PROD-2426494-2276518","NWS-IDP-PROD-2426493-2276517","NWS-IDP-PROD-2426492-2276516","NWS-IDP-PROD-2426487-2276512","NWS-IDP-PROD-2426484-2276509","NWS-IDP-PROD-2426483-2276508","NWS-IDP-PROD-2426479-2276504","NWS-IDP-PROD-2426477-2276503","NWS-IDP-PROD-2426475-2276502","NWS-IDP-PROD-2426458-2276486","NWS-IDP-PROD-2426453-2276482","NWS-IDP-PROD-2426452-2276481","NWS-IDP-PROD-2426450-2276480","NWS-IDP-PROD-2426442-2276474","NWS-IDP-PROD-2426437-2276470","NWS-IDP-PROD-2426438-2276471","NWS-IDP-PROD-2426433-2276466","NWS-IDP-PROD-2426432-2276465","NWS-IDP-PROD-2426434-2276467","NWS-IDP-PROD-2426430-2276463","NWS-IDP-PROD-2426431-2276464","NWS-IDP-PROD-2426203-2276345","NWS-IDP-PROD-2426204-2276346","NWS-IDP-PROD-2426102-2276282","NWS-IDP-PROD-2426052-2276244","NWS-IDP-PROD-2426019-2276228","NWS-IDP-PROD-2425905-2276157","NWS-IDP-PROD-2425891-2276153","NWS-IDP-PROD-2425874-2276146","NWS-IDP-PROD-2425851-2276136","NWS-IDP-PROD-2425801-2276114","NWS-IDP-PROD-2425748-2276070","NWS-IDP-PROD-2425747-2276069","NWS-IDP-PROD-2425746-2276068","NWS-IDP-PROD-2425745-2276067","NWS-IDP-PROD-2425744-2276066","NWS-IDP-PROD-2425743-2276065","NWS-IDP-PROD-2425681-2276015","NWS-IDP-PROD-2424738-2275345","NWS-IDP-PROD-2421587-2272709","NWS-IDP-PROD-2419354-2270782"]]')])
And the javascript code:
mkTableArray: function() {
var myTableArray = [];
$("#alerts").each(function() {
var arrayOfThisRow = [];
var tableData = $(this).find('li');
if (tableData.length > 0) {
tableData.each(function() {
arrayOfThisRow.push($(this).attr("id"));
});
myTableArray.push(arrayOfThisRow);
}
});
var myJson = JSON.stringify(myTableArray);
return myJson;
}
function fetchNewAlerts() {
data = Alert.mkTableArray();
$.post( "fetchNew.py", {data}, function(data) {
$("#alerts").prepend(data);
$(".new").hide().fadeIn(1000);
});
}
And the python:
data = cgi.FieldStorage()
mfs = data.getvalue("data")
print(mfs)
for line in mfs:
print(line)
Python is treating the entire thing as one list item. So doing a, for x in y loop, only prints out what you see above. It's treating it as though all of the items in the list are actually one single item. And I do not know how, or I have not yet figured out how, to get each NWS-IDP-PROD-2426826 item, separately so I can test each iteration. I have tried .split(), but to no avail. Any help would be greatly appreciated. Thank you.
I must have had a brain lapse. I was able to accomplish my goal by doing this:
data = cgi.FieldStorage()
print ("Content-Type: text/html")
print ()
mfs = data.getvalue("data")
lines = mfs.split(",")
for feature in nwsJson:
if feature['properties']['id'] not in lines:
pass
else:
print("<li>" +feature['properties']['id']+ "</li>")

JavaScript/jQuery solution for looping through JSON objects

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

Trying to do JSON.parse but it doesnt like what i am doing with a returned string from my server

I was trying to return a string from my server which would be parsed into a javascript object. I keep getting an error though when it comes to the parsing process. I didnt know why. Maybe you know something that i do not.
My string looks like this:
{{"fname":"bob","lname":"jones"},{...}}
What i was trying to do is something like
var item = JSON.parse(myString);
It should be making item, an array of names so i could do something like:
for(var i = 0; i < item.length; i++){
alert(item[i].fname + " " + item[i].lname);
}
Is there something i am doing wrong? The above was a sample, but below is actually code snippet:
while (reader.Read())
{
if (reader["rt_id"] != DBNull.Value && reader["rt_name"] != DBNull.Value)
{
t = #"{""pValue"":""{ReportType},"+reader["rt_id"]+#""",""pText"":"""+reader["rt_name"]+#"""}";
returnContentsArray.Add(t);
}
}
returnContents = "{" + String.Join(",",returnContentsArray.ToArray()) + "}";
return returnContents;
On Client:
var item = JSON.parse(result);
That string is not valid JSON. {} represents an object, which needs to have keys. It seems you want an array, use [] instead.
returnContents = "[" + String.Join(",",returnContentsArray.ToArray()) + "]";
You need to use correct JSON format. It looks like the format you should be using is
[{"fname":"bob","lname":"jones"},{...}]
Which would return an array of objects. Just make user you can validate the JSON in JSONLint of similar before trying to change up your javascript code.

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).

JSON result containing only one item

I'm likely missing something with json and javascript.
[{"commentText":"Testing 123","userPosted":"maxfridbe"},
{"commentText":"Testing 23","userPosted":"maxfridbe"}]
Sometimes I get multiple responses which works with this code:
function(data)
{
var sel = this;
jQuery.each(data,
function()
{
sel.append("<li>"+ this.userPosted+ "-" + this.commentText + "</li>");
});
};
Sometimes I only get one response which breaks the above code:
[{"commentText":"another test again welcom","userPosted":"maxfridbe"}]
I know this is because the response is being treated differently than a list.
Looking for the answer to this I get a bit of a runaround. Any solution would be greatly appreciated.
In the second example you provide, it seems to be an array with only one item, if it's like that, it should work, but I think that you're getting only a single object like:
{"commentText":"another test again welcom","userPosted":"maxfridbe"}
If it's a single object $.each iterates over the object properties.
You could check if your data variable is not an array using $.isArray, and if is not, you can wrap it into a single element array, so the $.each function will still work as expected:
//..
if (!jQuery.isArray(data)) data = [data]; // if isn't an array, wrap it
jQuery.each(data, function() {
sel.append("<li>"+ this.userPosted+ "-" + this.commentText + "</li>");
});
//..
I think you should user some optional parameters in your each() function:
function(data)
{
var sel = this;
jQuery.each(data,
function(i, item)
{
sel.append("<li>"+ item.userPosted+ "-" + item.commentText + "</li>");
});
};
using THIS keyword creates confusion in your case
Hope this helps
Playing around with CMS's solution made me realize that data was just a string somehow so:
if (!jQuery.isArray(data)) data = eval(data);
worked because then the data was an object. Not sure why when there are multiple results it does an eval for you.

Categories