user460114 user460114 - 3 years ago 227
jQuery Question

Parse coldfusion serialized array using jQuery

I have a coldfusion function that returns the following string to a jQuery function. This may not be the best way to do it, but I'm stuck with it for now.

var str = '1^Successfully logged in^0^1^1^5^NULL^xyz^100';


The coldfusion function was recently updated to generate an array of structs from a query, serialize it, then append it to the return string. The resulting string received by the jQuery function is now as follows:

var str = '1^Successfully logged in^0^1^1^5^NULL^xyz^100^[[4,"No credit card"],[5,"Test"]]'


Up until we added the serialized array, we were simply parsing the string like this (simplified for this question):

var a = str.split("^")[0];
var b = str.split("^")[1];
var c = str.split("^")[2];
var d = str.split("^")[3] || -1;
var e = str.split("^")[4] || -1;
var f = str.split("^")[5] || -1;
var g = str.split("^")[6] || 0;
var h = str.split("^")[7] || 0;
var i = str.split("^")[8] || 0;


How can I parse the array at the end of the string so that it does something like the following (this is essentially pseudocode and likely needs a loop):

var errors = str.split("^")[9];
if(we find an error of "4"){
$('#divAlert').html('No credit card')
}
if(we find an error of "5"){
$('#divAlert2').html('Test')
}

Answer Source

You can parse the 9th array position:

var f = JSON.parse(str.split("^")[9] || '[]');

Consider to cache the str.split("^").

The result of this is:

var str = '1^Successfully logged in^0^1^1^5^NULL^xyz^100^[[4,"No credit card"],[5,"Test"]]'

var tmpArr = str.split("^");
var a = tmpArr[0];
var b = tmpArr[1];
var c = tmpArr[2];
var d = tmpArr[3] || -1;
var e = tmpArr[4] || -1;
var f = tmpArr[5] || -1;
var g = tmpArr[6] || 0;
var h = tmpArr[7] || 0;
var i = tmpArr[8] || 0;
var f = JSON.parse(tmpArr[9] || '[]');
console.log(f);
f.forEach(function(ele, idx) {
    switch (ele[0]) {
        case 4:
            $('#divAlert').html((idx, e) => {return e + ele[1] + '<br/>'});
            break;
        case 5:
            $('#divAlert').html((idx, e) => {return e + ele[1] + '<br/>'});
            break;
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div id="divAlert"></div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download