JSON.parse(): unexpected character with websockets and xmpp kaazing gateway - javascript

I am trying to send a message using the XmppClient.js of kaazing, but I get an : SyntaxError: JSON.parse: unexpected character. The code in javascript is :
var client = new XmppClient(...);
var txtClient = new XmppRoom(...);
sendFromEditor : function(char){
var json = JSON.stringify(char);
//alert(json);
txtClient.sendMessage(json);
};
and I am receiving messages :
txtClient.onmessage = function(msg) {
var data = JSON.parse(msg.body);
alert(data);
The problem is in JSON.parse. The messages I am trying to send are very small (one char).
I also tried to change the maximum message size of kaazing gateway just in case but with no lack!
Any ideas?
Thanks in advance.

I could suggest to surround it with a try catch to check the exact error.. not sure if that helps ;)

Related

removing the backslashes in json string using the javascript

i have JSON response which is having backslashes and some responses are not containing the backslashes.
I need to show error message based on the response, How do i parse the JSON response using javascript?
JSON response with out backslashes,
{"_body":{"isTrusted":true},"status":0,"ok":false,"statusText":"","headers":{},"type":3,"url":null}
response with backslashes,
{"_body":"{\"timestamp\":\"2016-11-18T04:46:18.972+0000\",\"status\":500,\"error\":\"Internal Server Error\",\"exception\":\"java.lang.ArrayIndexOutOfBoundsException\",\"message\":\"1\",\"path\":\"/login\"}","status":500,"ok":false,"statusText":"Internal Server Error"}
i tried in the following way but it is working only for JSON response which is not having the backslashes.
var strj = JSON.stringify(err._body);
var errorobjs = strj.replace(/\\/g, "");
Actually the problem is not with / slashs. The JSON is INVALID.
remove these " from backend server
{"_body":"{\"timestamp\":\"2016-11-18T04:46:18.972+0000\",\"status\":500,\"error\":\"Internal
Server
Error\",\"exception\":\"java.lang.ArrayIndexOutOfBoundsException\",\"message\":\"1\",\"path\":\"/login\"}","status":500,"ok":false,"statusText":"Internal
Server Error"}
double quote before "{"timestamp and one after login"}"
these two highlighted and your code will work.
var data = '{"_body":{\"timestamp\":\"2016-11-18T04:46:18.972+0000\",\"status\":500,\"error\":\"Internal Server Error\",\"exception\":\"java.lang.ArrayIndexOutOfBoundsException\",\"message\":\"1\",\"path\":\"/login\"},"status":500,"ok":false,"statusText":"Internal Server Error"}';
var json_data = JSON.parse(data);
console.log(json_data);
You are actually wrapping body object in string at backend which is not valid.
"body" : "bodyOBJ" //Invalid
"body" : bodyObj //Valid
var obj = JSON.parse(response)
if(typeof obj._body == "string") {
obj._body = JSON.parse(obj._body)
}
console.log(obj);
Solution:
var response = {"_body":"{\"timestamp\":\"2016-11-18T04:46:18.972+0000\",\"status\":500,\"error\":\"Internal Server Error\",\"exception\":\"java.lang.ArrayIndexOutOfBoundsException\",\"message\":\"1\",\"path\":\"/login\"}","status":500,"ok":false,"statusText":"Internal Server Error"};
var body = JSON.parse(response._body);
console.log(body.error);
Explanation:
You have a top level object with one key, _body. The value of that key is a string containing JSON itself. This is usually because the server side code didn't properly create the JSON. That's why you see the \" inside the string. Unless you are able to fix the server side code, you have to decode the nested JSON manually.

Is it possible to modify a variable in Postman

I'm using Postman and I am trying to chain together some requests. There is an identity string that is generated in my first request that I would like to use in my second request e.g. similar to searching for a product, and then adding that product to basket.
Now I've been able to pull the value from the first request and I can pick that up in the second request. The problem is that the identity string has an ampersand in it. When I post the second request, it throws an error because the ampersand has not been escaped in the string. I would like to replace the ampersand in the variable with "&" but I can't get this to work.
I'm new to JavaScript so I imagine this is where the problem is. In Postman I have:
var jsonObject = xml2Json(responseBody);
console.log(jsonObject);
postman.setEnvironmentVariable("ItineraryId", jsonObject.ItineraryId);
ItineraryId.replace("&","&");
This returns "There was an error in evaluating the test script: ItineraryId is not defined". So I tried:
var jsonObject = xml2Json(responseBody);
console.log(jsonObject);
var oldId = postman.setEnvironmentVariable("ItineraryId", jsonObject.ItineraryId);
oldId.replace("&","&");
And got "There was an error in evaluating the test script: Cannot read property 'replace' of undefined"
Thanks in advance.
Figured it out!
var jsonObject = xml2Json(responseBody);
console.log(jsonObject);
var itineraryId = jsonObject.ItineraryId;
itineraryId = itineraryId.replace("&","&");
postman.setEnvironmentVariable("ItineraryId", itineraryId);
You should user pm.collectionVariables.set like in example below :
pm.collectionVariables.set("userId", pm.response.headers.get('Location').replace(pm.environment.get("api_url") + "/api/users/", ""));
In this example after POST on /api/users in response header : Location we receive link to new resource. You can use other variables like : pm.environment.get("api_url")

Google Script: JSON.parse fails for no apparent reason

I have this function in google script that fetches a JSON from the web, but it fails when i try to execute it, citing:
SyntaxError: Unexcpected character in string: '\''
Script:
function getTheFeed(url){
var response = UrlFetchApp.fetch(url);
var json = response.getContentText();
var Jdata = JSON.parse(json);
Jdata = json;
return Jdata;
}
I've tested the URL, by importing it in a string and doing JSON.parse on it, and i get no errors in Google Chrome.
Any other ideas?
UPDATE: After doing Logger.Log turns out the JSON is being cut after 8KB of response. Nothing conflicting at the place the request ends...
Still looking for a response...
Try to use alert(url) and see what you really get.
It could be an escaping issue which sometimes browsers handle properly when you enter it directly in the address bar.
EDIT:
Different browsers have different limits. But generally the limit is around 2,000 characters for the GET method of a URL.
See:
What is the character limit on URL

JSON invalid character error

when json is sent from the VB.net it sends it as text. When I inspect the data parameter in the ajax success I see data = [{'PageInformation':'test'}]
But in the following I get invalid character error --WHY?
var dataObj = jQuery.parseJSON(data);
Use double quotes: data = [{"PageInformation":"test"}]

I keep getting "Uncaught SyntaxError: Unexpected token o"

I'm trying to learn some html/css/javascript, so I'm writing myself a teaching project.
The idea was to have some vocabulary contained in a json file which would then be loaded into a table. I managed to load the file in and print out one of its values, after which I began writing the code to load the values into the table.
After doing that I started getting an error, so I removed all the code I had written, leaving me with only one line (the same line that had worked before) ... only the error is still there.
The error is as follows:
Uncaught SyntaxError: Unexpected token o
(anonymous function)script.js:10
jQuery.Callbacks.firejquery-1.7.js:1064
jQuery.Callbacks.self.fireWithjquery-1.7.js:1182
donejquery-1.7.js:7454
jQuery.ajaxTransport.send.callback
My javascript code is contained in a separate file and is simply this:
function loadPageIntoDiv(){
document.getElementById("wokabWeeks").style.display = "block";
}
function loadWokab(){
//also tried getJSON which threw the same error
jQuery.get('wokab.json', function(data) {
var glacier = JSON.parse(data);
});
}
And my JSON file just has the following right now:
[
{
"english": "bag",
"kana": "kaban",
"kanji": "K"
},
{
"english": "glasses",
"kana": "megane",
"kanji": "M"
}
]
Now the error is reported in line 11 which is the var glacier = JSON.parse(data); line.
When I remove the json file I get the error: "GET http://.../wokab.json 404 (Not Found)" so I know it's loading it (or at least trying to).
Looks like jQuery takes a guess about the datatype. It does the JSON parsing even though you're not calling getJSON()-- then when you try to call JSON.parse() on an object, you're getting the error.
Further explanation can be found in Aditya Mittal's answer.
The problem is very simple
jQuery.get('wokab.json', function(data) {
var glacier = JSON.parse(data);
});
You're parsing it twice. get uses the dataType='json', so data is already in json format.
Use $.ajax({ dataType: 'json' ... to specifically set the returned data type!
Basically if the response header is text/html you need to parse, and if the response header is application/json it is already parsed for you.
Parsed data from jquery success handler for text/html response:
var parsed = JSON.parse(data);
Parsed data from jquery success handler for application/json response:
var parsed = data;
Another hints for Unexpected token errors.
There are two major differences between javascript objects and json:
json data must be always quoted with double quotes.
keys must be quoted
Correct JSON
{
"english": "bag",
"kana": "kaban",
"kanji": "K"
}
Error JSON 1
{
'english': 'bag',
'kana': 'kaban',
'kanji': 'K'
}
Error JSON 2
{
english: "bag",
kana: "kaban",
kanji: "K"
}
Remark
This is not a direct answer for that question. But it's an answer for Unexpected token errors. So it may be help others who stumple upon that question.
Simply the response is already parsed, you don't need to parse it again. if you parse it again it will give you "unexpected token o" however you have to specify datatype in your request to be of type dataType='json'
I had a similar problem just now and my solution might help. I'm using an iframe to upload and convert an xml file to json and send it back behind the scenes, and Chrome was adding some garbage to the incoming data that only would show up intermittently and cause the "Uncaught SyntaxError: Unexpected token o" error.
I was accessing the iframe data like this:
$('#load-file-iframe').contents().text()
which worked fine on localhost, but when I uploaded it to the server it stopped working only with some files and only when loading the files in a certain order. I don't really know what caused it, but this fixed it. I changed the line above to
$('#load-file-iframe').contents().find('body').text()
once I noticed some garbage in the HTML response.
Long story short check your raw HTML response data and you might turn something up.
SyntaxError: Unexpected token o in JSON
This also happens when you forget to use the await keyword for a method that returns JSON data.
For example:
async function returnJSONData()
{
return "{\"prop\": 2}";
}
var json_str = returnJSONData();
var json_obj = JSON.parse(json_str);
will throw an error because of the missing await. What is actually returned is a Promise [object], not a string.
To fix just add await as you're supposed to:
var json_str = await returnJSONData();
This should be pretty obvious, but the error is called on JSON.parse, so it's easy to miss if there's some distance between your await method call and the JSON.parse call.
Make sure your JSON file does not have any trailing characters before or after. Maybe an unprintable one? You may want to try this way:
[{"english":"bag","kana":"kaban","kanji":"K"},{"english":"glasses","kana":"megane","kanji":"M"}]
const getCircularReplacer = () => {
const seen = new WeakSet();
return (key, value) => {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) {
return;
}
seen.add(value);
}
return value;
};
};
JSON.stringify(tempActivity, getCircularReplacer());
Where tempActivity is fething the data which produces the error "SyntaxError: Unexpected token o in JSON at position 1 - Stack Overflow"

Categories

Resources