string.search() function cannot parse string from XML response - javascript

I'm using someresponse.getBody(); to store the XML response I'm getting back from a webservice. When I pass this to the below function, it's not able to be parsed corrected using search() or indexOf(). Both return a start and end pos of 10 and -1.
However, when I pulled the body of the response from the execution logs and hard coded the variable with that value. When I pass that value to the same function, it is processed as I expect.
This looks to be a format issue. Any idea what I can do here?
I'm restricted to just using Javascript or NetSuite API's and the code runs server side.
I call the function using: var xmlCCConnote = getValue('CCConnote', response);
function getValue(tag,xmlString){
var value;
var tempString;
var startTag,endTag;
var startPos,endPos;
startTag = "<"+tag+">";
endTag = "</"+tag+">";
tempString=xmlString;
startPos = tempString.indexOf(startTag) + startTag.length;
nlapiLogExecution('DEBUG', 'startPos = ', startPos);
endPos = tempString.indexOf(endTag);
nlapiLogExecution('DEBUG', 'endPos = ', endPos);
value = tempString.slice(startPos,endPos);
return value;
}

The xmlstring I was passing into the function was escaped. The following fixed the issue:
startTag = '<'+tag+'>';
endTag = '</'+tag+'>';

Related

JSON.parse returns string instead of object

im writing a websocket client and i would like to receive messages as json strings. For this I need a login. And if the login isn't true i send a json string with nosuccess.
JSON String:
{"action":"login","args":["nosuccess"]}
On the client I'm using this to get the string:
WebSocket socket = new WebSocket("ws://localhost:2555/api");
socket.onmessage = function(evt) {
console.log(evt.data);
console.log(typeof(evt.data));
onMessage(evt);
}
function onMessage(evt) {
var data = JSON.parse(evt.data);
var action = data.action;
var args = data.args;
console.log(data);
console.log(typeof(data));
console.log(action);
console.log(args);
But the type of data is a string...
But why?
evt.data returns:
"{\"action\":\"login\",\"args\":[\"nosuccess\"]}"
data returns:
{"action":"login","args":["nosuccess"]}
The WebSocket server is a jetty Server which sends a string and a string array in json parsed in json with gson.toJson(class) Gson by Google. The Class is a class containing String action and String array args.
Complete source code of websocket.js:
var socket;
function openWebsocket(adress) {
socket = new WebSocket(adress);
socket.onopen = function(evt) {
console.log("Socket opened [" + adress + "]");
};
socket.onclose = function(evt) {
loadPage("login.html");
console.log("Socket closed [" + evt.code + "]");
}
socket.onmessage = function(evt) {
onMessage(evt);
}
socket.onerror = function(evt) {
console.log("Socket couldn't connect [" + evt.message + "]");
showMessage("fa-exclamation-circle", "Socket couldn't be established!", 1000);
}
}
function onMessage(evt) {
var data = JSON.parse(evt.data);
var action = data.action;
var args = data.args;
console.log(data);
console.log(typeof(data));
console.log(action);
console.log(args);
$(".card-container h3").html(data);
if(action == "login") {
if(args[0] == "success") {
loadPage("dashboard.htm");
currentpage = "dashboard.htm";
showMessage("fa-check", "Du wurdest erfolgreich eingeloggt", 2000);
} else if(args[0] == "nosuccess") {
loadPage("login.html");
currentpage = "login.html";
showMessage("fa-exclamation-circle", "Falscher Benutzername oder falsches Passwort", 2000);
} else if(args[0] == "unauthenticated") {
loadPage("login.html");
currentpage = "login.html";
showMessage("fa-exclamation-circle", "Login failure: not authenticated", 2000);
}
}
}
function sendMessage(json) {
$(".card-container h3").html(JSON.stringify(json));
console.log(JSON.stringify(json));
socket.send(JSON.stringify(json));
}
If I change this line:
var data = JSON.parse(evt.data);
to this:
var data = JSON.parse("{\"action\":\"login\",\"args\":[\"nosuccess\"]}");
Then it is a json object, but when I use evt.data then it is a string.
If I change the line to this:
var data = JSON.parse(JSON.parse(evt.data));
Then it works, but why, normally it should do it with only one JSON.parse, should it?
This seems to be fairly consistent with over-stringified strings. For example I loaded a text file using FileReader.readAsText that came with \n and \r which rendered in the console, so I did - (JSON.stringify(reader.result)).replace(/(?:\\[rn])+/g, '') first to see the symbols, then to get rid of them. Taking that and running JSON.parse() on it converts it to a non-escaped string, so running JSON.parse() again creates an object.
If you do not stringify your string, it will convert to an object and often it is not necessary but if you have no control over the obtained value, then running JSON.parse() twice will do the trick.
#DerpSuperleggera is correct. The issue was indeed an over-stringified string
let arr = "[\"~#iM\",[\"is_logged_out_token\",false,\"token_type\",\"Bearer\"]]"
So to parse it as an object, I just ran it through JSON.parse twice and that did the trick!
let obj = JSON.parse(JSON.parse(arr))
As others have stated in the comments it seems that this issue has been solved. If you are receiving a response from the server as a "stringified object" then you can turn it into a normal object with JSON.parse() like so:
var stringResponse = '{"action":"login","args":["nosuccess"]}';
var objResponse = JSON.parse(stringResponse);
console.log(objResponse.args);
You can also try out the above code here.
As for why the server is returning a string when you really wanted an object, that really comes down to your backend code, what library you are using, and the transport protocol. If you just want your front-end code to work, use JSON.parse. If you want to edit how the backend responds, please provide more information.
The checked response is correct in that it seems to be an issue of over-stringified strings. I came across it from using AWS Amplify AWSJSON type in my project. The solution that worked for me was to iterate multiple (twice) to get an object.
Wrote a simple JS function that when used to parse will return an object. There isn't really error checking, but a starting point.
export function jsonParser(blob) {
let parsed = JSON.parse(blob);
if (typeof parsed === 'string') parsed = jsonParser(parsed);
return parsed;
}

MobileFirst POST javascript array to java array

I have an array in javascript that I am trying to pass to my mobilefirst java adapter. I call my adapter like so,
myArr = [1,2,3];
var sendPost = new WLResourceRequest(
"/adapters/MyAdpater/path",
WLResourceRequest.POST
);
var formParam = {"arr":myArr};
sendTicketPost.sendFormParameters(formParams);
Then in my adapter I can have my method and get the param
public JSONObject postAdapterFx(#FormParam("arr") List<Integer> myArray) {}
Currently when I send this I just get a 400 error and it is because the adapter doesnt like the form param as that type, so what else could I set myArray to in the adapter? I can send it as a string and then convert the string to a List<Integer> in the java but that is really messy and I would like to avoid doing that.
So how can I pass this array?
Thanks for the help
you can do it in body with request.send(yourArray). Then you can read it in Java with buffer.
Example from knowledge center
var request = WLResourceRequest(url, method, timeout);
request.send(json).then(
function(response) {
// success flow
},
function(error) {
// fail flow
}
);
You will need to take an extra step before sending the form data to the adapter. sendFormParameters only accepts objects with simple values i.e., string, integer, and boolean; in your case arr is an array.
Create a utility function that will encode the form data, you can use the following:
function encodeFormData(data) {
var encoded = '';
for(var key in data) {
var value = data[key];
if(value instanceof Array) {
encoded += encodeURI(key+'='+value.join('&'+key+'='));
} else {
encoded += encodeURI(key+'='+value);
}
encoded += '&';
}
return encoded.slice(0, -1);
}
Then you will need to update your code as follows:
var myArr = [9,2,3];
var sendPost = new WLResourceRequest("/adapters/Cool/users/cool", WLResourceRequest.POST);
var formParam = {"arr" : myArr};
sendPost.sendFormParameters(encodeFormData(formParam));

javascript object, how to assign base64 type

I am using SecuGen device and its library.
I wrote following code
function fnCapture() {
document.frmmain.objFP.Capture();
var result = document.frmmain.objFP.ErrorCode;
if (result == 0) {
//var strimg1 = objFP.ImageTextData;
var strmin = document.frmmain.objFP.MinTextData;
//document.frmmain.min.value = strmin;
document.frmdata.Thumb.value = strmin;
}
else
alert('Failed during captured - ' + result);
return;
}
And then I am passing document.frmdata.Thumb to server side to a webservice. But webservice provider are saying that "you are sending an invalid base64"
There is a property like
document.frmdata.Thumb.ContentType
But I am not sure how to send this in base64.
Any help will be apprecited
If the data is a string you could use the btoa() function on the window object:
console.log(document.frmdata.Thumb.value);
> "088BA76AFE122" Some raw string value from scanner
window.btoa(thumb);
> "MDg4QkE3NkFGRTEyMg==" Base-64 encoded string

Add A Table Row With Ajax Results

I have a function that takes the values returned from an ajax call and adds a row to a table that is defined in the json values, but I don't think it is fetching the table correctly. Is there anything special I need to be doing? I know the data['table_name'] variable does have the correct value in it.
Here is the code I have.
function ajaxSuccess () {
var data = JSON.parse(this.responseText);
var elementObj = document.getElementById(data['table_name']);
var i = elementObj.size() + 1;
elementObj.append('<tr><td>Date</td><td>Name</td><td>' + data['new_comment'] + '</td></tr>');
i++;
return false;
}
This is not correct.
You have js variable var elementObj = document.getElementById(data['table_name']);
And you use jquery append().
Try var elementObj = $("#"+data['table_name']); instead.
Also check console for errors, you are probably receiving this:
Uncaught TypeError: Object #<HTMLDivElement> has no method 'append'
p.s. you can also try this:
$(elementObj).append('<tr><td>Date</td><td>Name</td><td>' + data['new_comment'] + '</td></tr>');
without rewriting var elementObj to jquery variable.

jQuery getJSON never enters its callback function

I've been sitting with this for hours now, and I cant understand why.
q is working. The URL does give me a proper JSON-response. It shows up as objects and arrays and whatnot under the JSON tab under the Net-tab in Firebug and all is fine. I've also tried with other URLs that i know work. Same thing happens.
I have another function elsewhere in my tiny app, wihch works fine, and is pretty much exactly the same thing, just another API and is called from elsewhere. Works fine, and the data variable is filled when it enters the getJSON-function. Here, data never gets filled with anything.
I've had breakpoints on every single line in Firebug, with no result. Nothing happens. It simply reaches the getJSON-line, and then skips to the debugger-statement after the function.
var usedTagCount = 10;
var searchHits = 20;
var apiKey = "a68277b574f4529ace610c2c8386b0ba";
var searchAPI = "http://www.flickr.com/services/rest/?method=flickr.photos.search&" +
"format=json&api_key=" + apiKey + "&sort=interestingness-desc&per_page="
+ searchHits + "&jsoncallback=?&nojsoncallback=1&tags=";
var tagString = "";
var flickrImageData = new Array();
function search(query) {
for(var i = 0; i < usedTagCount; i++) {
tagString += query[i].key + ",";
}
var q = searchAPI + tagString;
$.getJSON(q, function(data) {
debugger; /* It never gets here! */
$.each(data.photos.photo, function(i, item) {
debugger;
flickrImageData.push(item);
});
});
debugger;
return flickrImageData;
}
Example of request URL (q):
http://www.flickr.com/services/rest/?method=flickr.photos.search&format=json&api_key=a68277b574f4529ace610c2c8386b0ba&sort=interestingness-desc&per_page=20&jsoncallback=?&tags=london,senior,iphone,royal,year,security,project,records,online,after,
I do wonder, since JSONView (the firefox plugin) cannot format it properly, that it isn't really JSON that is returned - the mime-type is text/html. Firebug, however, interprets it as JSON (as i stated above). And all the tag words come from another part of the app.
I think you might need to remove the
nojsoncallback=1
from your searchAPI string.
Flickr uses JSONP to enable cross domain calls. This method requires the JSON to be wrapped in a json callback, the nojsoncallback=1 parameter removes this wrapping.
EDIT: Apparently it works with nojsoncallback=1, I got this piece of code to work for me. What jQuery version are you using? JSONP is only available from 1.2 and up.
This works for me (slight modifications):
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
var usedTagCount = 1;
var searchHits = 20;
var apiKey = "a68277b574f4529ace610c2c8386b0ba";
var searchAPI = "http://www.flickr.com/services/rest/?method=flickr.photos.search&" +
"format=json&api_key=" + apiKey + "&sort=interestingness-desc&per_page="
+ searchHits + "&jsoncallback=?&nojsoncallback=1&tags=";
var tagString = "";
var flickrImageData = new Array();
function search(query) {
tagString = query;
var q = searchAPI + tagString;
$.getJSON(q, function(data) {
$.each(data.photos.photo, function(i, item) {
debugger;
flickrImageData.push(item);
});
});
}
search("cat");
</script>
When I try the url: http://www.flickr.com/services/rest/?method=flickr.photos.search&format=json&api_key=a68277b574f4529ace610c2c8386b0ba&sort=interestingness-desc&per_page=10&tags=mongo
it returns data, as it should -
try to change the getJSON to an $.ajax() and define a function jsonFlickrApi (data)
with the code you have in you callback function.
If that don't work - please post code to at jsbin.com <- so we can try it live - so much easier to debug.

Categories