Valid JSON (for real) is throwing error in JSON.Parse - javascript

I am at a dead end. I am baffled. I am passing a stringified dictionary from Python (using json.dumps()) through UDP to an Ionic 2 (Typescript) application.
The python code generating the messages:
message = { 'time' : str(round(float(op('indexFraction')[0]),3)) }
messageJSON = json.dumps(message)
#messageJSON = json.JSONEncoder().encode(message)
print(messageJSON)
op('udpout').send(messageJSON) #sending out of TouchDesigner
My callback function on the Ionic side looks like this:
socket.on('message', function (message, remoteAddress) {
if (message.length > 0) {
console.log(message, typeof(message));
// alert(message);
// process response message
var data = JSON.parse(message);
console.log(data);
if (data.time) {
alert(data.time);
}
}
});
A sample message looks like this (typeof string):
{"time": "0.934"}
// this is a string, as evidenced by the Console.log
JSON.parse() throws the following:
index.html:1 Uncaught SyntaxError: Unexpected token in JSON at position 17
I've tried all kinds of variants on the object. It passes as valid on JSONlint. It's so simple, no wacky characters. Any ideas?
Thanks,
Marc

Related

Uncaught (in promise) SyntaxError: Unexpected token N in JSON at position 0

I have made a small vanilla javascript code to fetch api but it is throwing the error "Uncaught (in promise) SyntaxError: Unexpected token N in JSON at position 0". I m not able to understand, exactly why the error is caught. Can somebody help me to resolve this.
const config = {
url: "https://randomuser.me/",
numberCards: 24
};
fetch(`${config.url}&amount=${config.numberCards}`)
.then(function(response) {
return response.json();
})
.then(function(apiResponse) {
// Output API response to console to view.
console.log(apiResponse);
});
It's because of this.
const config = {
url: "https://randomuser.me/",
numberCards: 24
};
fetch(`${config.url}&amount=${config.numberCards}`)
It should be,
const config = {
url: "https://randomuser.me/api/",
numberCards: 24
};
fetch(`${config.url}?amount=${config.numberCards}`)
It's because the json data are from "https://randomuser.me/api/". Not "https://randomuser.me/". And the query strings must begin with a "?" mark. "&" mark is used to separate query strings. (like this "https://example.com/?amount=24&hi=en")

Why I get a error encrpyting a message with Openpgpjs?

I am trying to implement openpgpjs on my application because I need to encrypt a string using a public key (PGP). I tested this jsfiddle (https://jsfiddle.net/gu72bzm8/) which encrypts a string using a public key, it works very well. I even tested it with different keys and strings.
var message = "secret message";
const encryptMessage = async() => {
if(window.crypto.getRandomValues){
if(message != ""){
const publicKeyString = document.getElementById("pubkey").innerHTML;
var options = {
message: openpgp.message.fromText(message),
publicKeys: (await openpgp.key.readArmored(publicKeyString)).keys
};
openpgp.encrypt(options).then(ciphertext => {
alert(ciphertext.data);
})
}
} else{
window.alert("This browser does not support basic cryptography!");
}
}
encryptMessage();
However, if I copy exactly that code and try to run it locally (using the same cdn of that fiddle) I get the following error:
Uncaught (in promise) Error: Error encrypting message: No keys, passwords, or session key provided.
How can I fix it?

request.form() throws 'undefined is not a function' error in Node

I want to create a form on a request in Node to add attachments to an email. As far as I can tell here under the multipart/form-data (Multipart Form Uploads) section I should be able to create a request form using
var r = request.form()
But I am getting this error in the console.
var fd = request.form();
^
TypeError: undefined is not a function
Can anyone tell me why this is happening and how to fix it. Thanks in advance!
UPDATE
Looking at the linked documentation, and on the advice of Chris G below, again I changed my code to look like this:
var r = request.post(reqOptions, function (err, resp) {
//console.log(resp.body);
//console.log(resp.statusCode);
if (err) {
return deferred.reject({
code: _.get(resp, 'statusCode'),
reason: err.message || err.errmsg
});
} ...
);
var form = r.form();
form.append('attachmentA',fs.createReadStream(path.join(__dirname, 'abc.jpg')));
Now I get the following error.
{ code: undefined, reason: 'write after end' }

Parse SDK JavaScript with Node.js ENOTFOUND

So I want to fetch a large amount of data on Parse, a good solution I found is to make a recursive function: when the data are successfully found, launch another request. The way I'm doing it is pretty simple:
var containedLimit = 1000, // Also tried with 500, 300, and 100
parseUsersWaiting = {
// A lot of Users
},
parseUsers = {}, // Recipt for Users
getPlayers = function (containedIn) {
var count = 0;
if (containedIn == undefined) {
containedIn = [];
for (var i in parseUsersWaiting) {
count++;
if (count > containedLimit) {
break;
}
containedIn.push(parseUsersWaiting[i].id);
delete parseUsersWaiting[i];
}
}
var UserObject = Parse.Object.extend('User'),
UserQuery = new Parse.Query(UserObject);
UserQuery.limit(containedLimit);
UserQuery.containedIn('objectId', containedIn);
UserQuery.find({
success: function (results) {
if (results) {
for (var i in results) {
if (parseUsers[results[i].id] == undefined) {
parseUsers[results[i].id] = results[i];
}
// Other stuff
if (results.length < containedLimit) {
// End of process
} else {
getPlayers();
}
}
} else {
// Looks like an end of process too
}
}, error: function (error) {
console.log(error.message);
getPlayers(containedIn);
}
});
};
Now, here is what I would like to call the "issue": it happen, very frequently, that the "error" callback is launched with this:
Received an error with invalid JSON from Parse: Error: getaddrinfo ENOTFOUND api.parse.com
at errnoException (dns.js:44:10)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:94:26)
(With code 107, of course) So I searched on the Parse Documentation, and it says the exact same thing: "Received an error with invalid JSON". Yeah.
I'm using the Parse SDK provided by Parse.com (npm install parse)
I also tried to modify a bit the Parse code with replacing the host key by 'hostname' on line 361 of the file parse/node_modules/xmlhttprequest/lib/XMLHttpRequest.js (Parse package version: 1.5.0), and it didn't worked, so I removed my changes.
(By the way, I found a solution talking about using ulimit to change memory usage limit that could solve the problem, but actually, I haven't the necessary rights to execute this command)
This error occurs when it can not connect to the API (technically when it cannot lookup the IP address of the API server). Perhaps your internet connection was lost for a brief moment or their SDK server were unavailable (or maybe the server is denying your request due to rate limits).
Either way it is good to code some resilience into your application. I see your on error function retries the API call, but perhaps it would be worth adding a timeout before you do that to give the problem a chance to recover?
error: function (error) {
console.log(error.message);
setTimeout(getPlayers, 10000, containedIn);
}
If the sever is rate limiting your requests, this will also help.

JavaScript/Node.js JSON.parse() Undefined

I am receiving the error:
undefined:1
'{"completed_in":0.078,"max_id":333655176038719488,"max_id_str":"3336551760387
^
SyntaxError: Unexpected token '
at Object.parse (native)
at /home/tweets/10seconds.js:25:25
at passBackControl (/home/tweets/node_modules/oauth/lib/oauth.js:367:11)
at IncomingMessage.<anonymous> (/home/tweets/node_modules/oauth/lib/oauth.js:386:9)
at IncomingMessage.EventEmitter.emit (events.js:117:20)
at _stream_readable.js:895:16
at process._tickCallback (node.js:415:13)
When parsing Twitter API JSON from the Search API.
The code I am using the parse this JSON is:
MongoClient.connect("mongodb://localhost:27017/db", function(err, db) {
if(err) { return console.dir(err); }
var collection = db.collection("tweets");
while(run < 200){
oa.get("http://search.twitter.com/search.json?q=morning&rpp=100&include_entities=true&result_type=mixed", access_token, access_token_secret, function(error, data) {
var theTweets = JSON.parse(sys.inspect(data));
collection.insert(theTweets, {w:1}, function(err, result) {});
console.log(run);
});
run = run + 1;
}
});
What could cause this?
Probably, the output of sys.inspect is not JSON it adds the quote '.
Why are you using sys.inspect?
If data is a JSON string, then use JSON.parse(data); and if it's an object already, well you don't have to use JSON.parse at all...
The problem is on the sys.inspect() call as already stated by the other answers and comments.
As stated in the nodejs documentation (http://nodejs.org/api/util.html#util_util_inspect_object_options):
Return a string representation of object, which is useful for debugging.
By the way, it seems they changed the sys module name to util.
You can easily make a small test by running the following code on an older node version. It should throw your error:
var sys = require('sys');
var data = '{"test":1, "test2":2}';
sys.puts(JSON.parse(sys.inspect(data)));
And then remove the sys.inspect call. It should correctly parse the object:
var sys = require('sys');
var data = '{"test":1, "test2":2}';
sys.puts(JSON.parse(data));

Categories