I'm getting an 'Uncaught SyntaxError' while trying to parse a JSON string, and I can't figure out why.
It looks like message is a string, which seems to be a common problem, and the json appears to be valid. A snippet of my code is given. It fails on the var obj = ... line.
this.send = function (message) {
console.log(message);
console.log(message.toString());
console.log('{"ReadyToGo":1}');
console.log(typeof message);
var obj = $.parseJSON(message);
}
On the console, I get this just before the error.:
{"ReadyToGo":1}
{"ReadyToGo":1}
{"ReadyToGo":1}
string
Any ideas?
EDIT: Added console.log(typeof message), which yields 'string'
OK, I got this sorted. A null character ( '\0' ) was been appended to the string somewhere along the long call chain, and this wasn't visible in the debugger. Thanks to cookie monster for the heads-up on this one.
Everything works as soon as I strip out the null char.
Related
I am making a function in the Data-Type "Object",
Code:
Object.exists = function(obj){
if(typeof(obj)==="object"){
return true;
}else{
return false;
}
}
Its purpose is to check whether an object exists or not. Everything works fine if the object entered exists, but if I try to check an object which does not exist(I am trying to develop a function and am currently checking it), it throws an error. The code to check and the error msg:
Object.exists(demo); //Note: demo is not an object
//Error:
Uncaught ReferenceError: demo is not defined
at <anonymous>:1:15
and if I try to add demo in quotes, then it does not work and shows false even if I try to add an existing object. If I try
if(typeof(obj)==="object"){
return true;
}else{
return false;
}
}
the code above without the function and the object doesn't exist, no error is thrown.
So I tried to work out my dumb brain and thought that can I use eval(), but I don't think so. Is there any other way I can convert the parameter(even if it is a string) into an object for the if statement?
I just found out the answer,
used eval() and it worked!
The code:
Object.exists = function(obj){
var type = eval("typeof("+obj+")");
console.log(type);
}
When you try an object which exists, it logs object, but if you try anything other, it logs it's type.
I'm trying to get rid of the double quotes around the trading pair symbols I receive from a binance websocket. It sends real-time best bid and ask prices for all trading pairs on the platform. This means that it is recieving a lot of payloads very often. This is the websocket:
const WebSocket = require('ws');
ws = new WebSocket('wss://stream.binance.com:9443/ws/!bookTicker');
This chunk of code works fine as far as I know.
ws.on('open', function open() {
ws.send(JSON.stringify({
method: "SUBSCRIBE",
params: ['!bookTicker'],
id: 1
}));
});
This is where the problem is:
ws.on('message', function incoming(data) {
//sets fresh_symbol to a string of the trading pair symbol
let fresh_symbol = JSON.stringify(JSON.parse(data)['s']);
//tries to filter out if fresh_symbol is undefined, doesn't work.
if (typeof fresh_symbol != undefined){
console.log(fresh_symbol.replace(/['"]+/g, ''));
}
});
The websocket constantly receives payloads (perhaps many hundred per seconds, I'm not sure but it's a lot). If I tell the code to simply console.log the fresh_symbol variable, the code outputs just fine. The problem arises when I tell the code to output the fresh_symbol string but with the double quotes on either side removed using the .replace() method. Even using that if statement to filter out when the variable is undefined, I still get a TypeError that states that:
console.log(fresh_symbol.replace(/['"]+/g, ''));
^
TypeError: Cannot read property 'replace' of undefined
I assume this has something to do with the fact that the websocket is receiving payloads so fast that the fresh_symbol variable is occasionally being overwritten when it's being accessed, but I have no idea how to remedy this problem. The code runs for a second or two, outputing the symbols in the desired format, before stopping due to an error. I'm no pro when it comes to javascript so please forgive me if anything here seems obvious.
The error comes from the 'undefined filter':
if(typeof fresh_symbol != undefined)
should be:
if(typeof fresh_symbol != 'undefined')
since typeof returns a string of the type.
So there is an old code base I am leveraging from work, currently they are sending over 2 items from an object and I'm adding a third. The third object I'm sending in JAVA as a string, however in the communication over to javascript it's freaking out, I'm getting a horrible error as prototype is declaring it undefined, however I'm watching the code being sent.
Currently the Java code is calling the function. Passing the following data over. All of these are strings.
setCCInfo(xxxxxxxxxxxxxx2205, 1219, 60W76W);
When I remove the final variable, and pass just the first two the function works, however it's almost like prototype is expecting a numeral as I had to change the other two into strings when it got to the front end. I'll attach the code below. The current Error I'm getting is
"prototype-1.6.0.2.js:394 Uncaught SyntaxError: Invalid or unexpected
token
at prototype-1.6.0.2.js:394
at prototype-1.6.0.2.js:635
at prototype-1.6.0.2.js:595
at Array.forEach ()
at Array.each (prototype-1.6.0.2.js:594)
at Array.collect (prototype-1.6.0.2.js:634)
at String.evalScripts (prototype-1.6.0.2.js:394)
at Function. (prototype-1.6.0.2.js:209)
at prototype-1.6.0.2.js:231"
ctx.getResponse().getWriter().print(output.getString("TCResultStatus").toUpperCase());
StringBuilder str = buildJavascriptCall(cceft);
ctx.getResponse().getWriter().print(str.toString());
private StringBuilder buildJavascriptCall(CcEft cceft) {
StringBuilder str = new StringBuilder();
str.append("<script type='text/javascript'>setCCInfo(");
str.append(cceft.getMaskedCCNum());
str.append(", ");
str.append(cceft.getCombinedExpDate());
str.append(", ");
str.append(cceft.getBillingId());
str.append(");</script>");
return str;
}
I am getting an object as response for an api call
The object looks like below
Now when I try response._modifiedby_value I am getting the right response, but when I try response.createdby_value#OData.Community.Display.V1.FormattedValue I am getting the below error
Uncaught SyntaxError {message: "Unexpected token ILLEGAL"}
that's because '#' is a special character, therefore you can't do:
response.createdby_value#OData = 2;
but instead
response["createdby_value#OData"] = 2;
I have Angular service and in that service I have a code:
this.testMethod = function( ) {
this.jsonTest = "[{'id':'123','title':'XYZ','id2':'456','status':2}]";
this.parseTest(this.jsonTest);
};
this.parseTest = function(jsonTest) {
var jsonTestObj = JSON.parse(jsonTest); // I get error hear
}
Test method is getting called on ng-click event.
Error that I am getting while testing in latest chrome browser:
SyntaxError: Unexpected token ' at Object.parse (native)
......
I tried multiple things to fix it but nothing seems to work.
Every time I get undefined value error.
Basically I want to parse JSON object and get the values.
What am I doing wrong?
Use this
this.jsonTest = '[{"id":"123","title":"XYZ","id2":"456","status": "2"}]';
Or this
this.jsonTest = "[{\"id\":\"123\",\"title\":\"XYZ\",\"id2\":\"456\",\"status\": \"2\"}]";
You either need to use ' outside or " outside and escape the quotes inside.
Both the key and value need to be in double quotes.
You need to use double quotes in your string, other than that your code should work.
To quote from specification
A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.
Your JSON is not valid. Always check your JSON integrity in those cases, i personaly use
http://jsonlint.com/