JSON rows Extracting issue in JavaScript - javascript

I have following json data coming from server in which i want to extract LimitClass and LimitClassID and store their values in respective arrays.
{
"ErrorDesc":"",
"ErrorCode":"",
"LimitClassList":"[{\"LimitClass\":\"L16\\n\",\"LimitClassId\":\"32900\\n\"},{\"LimitClass\":\"28febL0\\n\",\"LimitClassId\":\"31901\\n\"},{\"LimitClass\":\"L14\\n\",\"LimitClassId\":\"31900\\n\"},{\"LimitClass\":\"L17\\n\",\"LimitClassId\":\"32950\\n\"},{\"LimitClass\":\"L15\\n\",\"LimitClassId\":\"31950\\n\"},{\"LimitClass\":\"L0\\n\",\"LimitClassId\":\"21901\\n\"},{\"LimitClass\":\"L4\\n\",\"LimitClassId\":\"23000\\n\"},{\"LimitClass\":\"OTC Send\\n\",\"LimitClassId\":\"30901\\n\"},{\"LimitClass\":\"L2\\n\",\"LimitClassId\":\"22900\\n\"},{\"LimitClass\":\"L12\\n\",\"LimitClassId\":\"28900\\n\"},{\"LimitClass\":\"L6\\n\",\"LimitClassId\":\"23900\\n\"},{\"LimitClass\":\"L1\\n\",\"LimitClassId\":\"25900\\n\"},{\"LimitClass\":\"L13\\n\",\"LimitClassId\":\"29900\\n\"},{\"LimitClass\":\"L7\\n\",\"LimitClassId\":\"24900\\n\"},{\"LimitClass\":\"L8\\n\",\"LimitClassId\":\"26900\\n\"},{\"LimitClass\":\"L10\\n\",\"LimitClassId\":\"27900\\n\"},{\"LimitClass\":\"L13\\n\",\"LimitClassId\":\"30900\\n\"},{\"LimitClass\":\"UatTesting123\\n\",\"LimitClassId\":\"32901\\n\"}]"
}
Here is the code I have tried :
var list = data.LimitClassList;
var arrayLimitClass = [];
var arrayLimitClassId = [];
for(var i in list) {
arrayLimitClass.push(list[i].LimitClass);
arrayLimitClassId.push( list[i].LimitClassId);
}
alert(list);
alert(arrayLimitClass);
alert(arrayLimitClassId);
List variable has following result when I alert it:
[{\"LimitClass\":\"L16\\n\",\"LimitClassId\":\"32900\\n\"},{\"LimitClass\":\"28febL0\\n\",\"LimitClassId\":\"31901\\n\"},{\"LimitClass\":\"L14\\n\",\"LimitClassId\":\"31900\\n\"},{\"LimitClass\":\"L17\\n\",\"LimitClassId\":\"32950\\n\"},{\"LimitClass\":\"L15\\n\",\"LimitClassId\":\"31950\\n\"},{\"LimitClass\":\"L0\\n\",\"LimitClassId\":\"21901\\n\"},{\"LimitClass\":\"L4\\n\",\"LimitClassId\":\"23000\\n\"},{\"LimitClass\":\"OTC Send\\n\",\"LimitClassId\":\"30901\\n\"},{\"LimitClass\":\"L2\\n\",\"LimitClassId\":\"22900\\n\"},{\"LimitClass\":\"L12\\n\",\"LimitClassId\":\"28900\\n\"},{\"LimitClass\":\"L6\\n\",\"LimitClassId\":\"23900\\n\"},{\"LimitClass\":\"L1\\n\",\"LimitClassId\":\"25900\\n\"},{\"LimitClass\":\"L13\\n\",\"LimitClassId\":\"29900\\n\"},{\"LimitClass\":\"L7\\n\",\"LimitClassId\":\"24900\\n\"},{\"LimitClass\":\"L8\\n\",\"LimitClassId\":\"26900\\n\"},{\"LimitClass\":\"L10\\n\",\"LimitClassId\":\"27900\\n\"},{\"LimitClass\":\"L13\\n\",\"LimitClassId\":\"30900\\n\"},{\"LimitClass\":\"UatTesting123\\n\",\"LimitClassId\":\"32901\\n\"}]
But I am getting dots (.) when I alert arrayLimitClass and arrayLimitClassId. What am I doing wrong in extracting rows of json Object?

"LimitClassList":"[{\"LimitClass\":\"L1....]"
^ ^
LimitClassList is a string, not an array. Make it so it is an actual array, than your code should work. There should be no reason to have to parse it again.

The value below data.LimitClassList is itself a String containing JSON. You have to decode this first.
var list = JSON.parse( data.LimitClassList );
var arrayLimitClass = [];
var arrayLimitClassId = [];
// ...
This is more or less a workaround. You should have a look at your server code and fix the encoding error there!

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 .

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

excel javascript API array handling

I'm working on an add-in for excel 2016 using the javascript API. I can successfully get the range into an array and get the values to show in console.log. I've also been able to get the values into a JSON array using JSON.stringify();
I need to manipulate the array to remove the empty values ("").
Can this be accomplished by using regular javascript array methods?
I'm thinking I can display the results back into a different worksheet using a similar approach like i did with var shWk
Here are some snippets of what I'm trying to do:
(function () {
"use strict";
// The initialize function must be run each time a new page is loaded
Office.initialize = function (reason) {
$(document).ready(function () {
app.initialize();
//document.getElementById("date").innerHTML = Date("MAR 30 2017");
$('#deleteTab').click(deleteTab);
$('#preview').click(preview);
$('#publish').click(publish);
});
};
function preview() {
Excel.run(function(ctx) {
//getting the colname from a date range in B2
var colName = ctx.workbook.worksheets.getItem('preview').getRange("B2");
colName.load('values');
return ctx.sync().then(function() {
//converting colname value to string for column name
var wkN = (colName.values).toString();
// displaying on the task pane
document.getElementById("tst").innerText = wkN;
// testing to confirm i got the correct colname
var shWk = ctx.workbook.worksheets.getItem('preview').getRange("B3");
shWk.values = colName.values;
//building the column connection by setting the table name located on a different worksheet
var tblName = 'PILOT_ZMRP1';
var tblWK = ctx.workbook.tables.getItem(tblName).columns.getItem(wkN);
//loading up tblWK
tblWK.load('values');
return ctx.sync().then(function(){
//this is where my question is:
var arry = tblWK.values;
for (var i=0; i < tblWK.length; i++){
if (tblWK.values !== ""){
arry.values[i][0]) = tblWK.values[i][0]
};
};
console.log(arry.length); //returns 185
console.log (arry.values);//returns undefined
tblWK.values = arry;
var tblWeek = tblWK.values;
console.log(tblWeek.length);//returns 185
console.log(tblWK.values);//returns [object Array] [Array[1],Array[2]
})
});
}).catch(function (error) {
console.log(error);
console.log("debug info: " + JSON.stringify(error.debugInfo));
});
}
What am I missing? Can you point me to some resources for javascript array handling in the specific context of office.js?
I want to thank everyone for the time spent looking at this question. This is my second question ever posted on Stack Overflow. I see that the question was not written as clear as it could've been. What i was trying to achieve was filtering out the values in a 1D array that had "". The data populating the array was from a column in a separate worksheet that had empty values (hence the "") and numeric values in it. the code below resolved my issue.
//using .filter()
var itm = tblWK.values;
function filt(itm){
return itm != "";
}
var arry = [];
var sht = [];
var j=0;
var s=0;
arry.values = tblWK.values.filter(filt);
//then to build the display range to show the values:
for (var i=0; i < itm.length-1; i++) {
if (tblWK.values[i][0]){
var arry; //tblWK.values.splice(i,0); -splice did not work, maybe my syntax was wrong?
console.log("this printed: "+tblWK.values[i][0]);
var cl = ('D'+i); //building the range for display
j++; //increasing the range
s=1;//setting the beignning range
var cll = cl.toString();//getRange() must be a string
console.log(cll);//testing the output
}
}
//using the variable from the for loop
var cl = ('D'+s+':D'+j);
var cll = cl.toString();
console.log(cll);//testing the build string
sht = ctx.workbook.worksheets.getItem('Preview').getRange(cll);
sht.values = arry.values; //displays on the preview tab
console.log (arry.values); //testing the output
The question was probably easier said by asking what vanilla javascript functions does office.js support. I found a lot help reading Building Office Add-ins using Office.js by Micheal Zlatkovsky and by reading the MDN documentation as well as the suggested answer posted here.
Regards,
J
I'm not sure what this check is trying to achieve: tblWK.values !== "". .values is a 2D array and won't ever be "".
For Excel, the value "" means that the cell is empty. In other words, if you want to clear a cell, you assign to "". null value assignment results in no-op.
You can just fetch the values form the array that contains null by using for each and can can push the null values into another array.

Parsing a localstorage object gives uncaught syntax error?

I'm trying to save numbers given by Math.random. I save them in array which gets saved into localStorage. I then want to append each new array of numbers when Math.random is used. It's easier if you view the code I tried wrting.
var nums = [];
for (var i = 0; i < 5; i++) {
var num = Math.floor(Math.random() * 50);
nums.push(" " + num);
}
console.log(nums);
function appendToStorage(name, data) {
var old = localStorage.getItem(name);
if (old === null) old = "";
localStorage.setItem(name, old + JSON.stringify(data));
}
if (localStorage.num) {
appendToStorage('num', nums);
} else {
localStorage.setItem("num", JSON.stringify(nums));
}
var nums2 = localStorage.getItem("num");
console.log(nums2);
document.getElementById("test").innerHTML = JSON.parse(nums2);
This doesn't work, though. Console says Uncaught SyntaxError: Unexpected token [
This error will work if you remove the JSON.parse on getElementById. I want it to be parsed, though, so the numbers are more easily viewed. How can I do this?
If you simply append a valid JSON string to another valid JSON string you don't get a valid JSON string. For example:
var myJSON = '{"thing": "data"}'; // valid
myJSON = myJSON + myJSON; // myJSON is now '{"thing": "data"}{"thing": "data"}', not valid
To do this reliably you'll need to parse your retrieved JSON, update the result, then stringify it again before storing it in localStorage.
function appendToStorage(name, data) {
var old = localStorage.getItem(name);
if (old === null) old = "[]";
var newData = JSON.parse(old);
newData.push(data);
localStorage.setItem(name, JSON.stringify(newData));
}
Note that this will return an array when you parse it, and that will cause you a problem when you try to set innerHTML. You'll need to unpack the array to some sort of text format first (thanks to jibsales for that).
Element.innerHTML takes a string as valid input, not an Array. May I suggest using JSON.parse(nums).join("");
Using this method would also allow you to not add the leading white space in your for loop and instead add the white space as the first parameter to the Array.join method. If you want each number on a new line, pass "\n".

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