JavaScript/Node.js JSON.parse() Undefined - javascript

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));

Related

SyntaxError: Unexpected token v in JSON at position 2

I am running a node.js server running express.js on my local machine and need to decode a request made by the client, that contains a json string in it. I run the code below and get the following error.
SyntaxError: Unexpected token v in JSON at position 2
at JSON.parse (<anonymous>)
at C:\myLocation\source\repos\server\server\server.js:144:19
at Layer.handle [as handle_request] (C:\myLocation\source\repos\server\server\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\myLocation\source\repos\server\server\node_modules\express\lib\router\index.js:317:13)
My request is
http://localhost:1337/%7B%22Code%22:%22VNdVwY9iWhFZ114CjcDZbY%22,%22Chat%22:%22Test.txt%22%7D
The expected json is
{"Code":"VNdVwY9iWhFZ114CjcDZbY","Chat":"Test.txt"}
I get the json, but it still gives me the same error.
My code:
app.use(function (req, res) {
//console.log(req.url)
var myStr = req.url.replace('/', '')
if (myStr != false) {
let decodeStr = decodeURIComponent(myStr)
var test = JSON.parse(decodeStr)
var json = JSON.stringify(test)
if (json.includes(createkey)) {
console.log("Create: " + json)
createFile(req, res, test)
} else if (json.includes(modKey)) {
console.log("Modify: " + json)
modifyFile(req, res, test)
} else if (json.includes(readFileKey)) {
console.log("Read: " + json)
readFile(req, res, test)
}
} else {
res.sendStatus(404)
console.log("home")
}
})
Why do I get the error?
Edit 1
I added console.log(decodeStr)but I still get the error. It returns {"Code":"VNdVwY9iWhFZ114CjcDZbY","Chat":"Test.txt"}
{"Code":"'GAHGAaphgAP:gjpaGHAHAG{AaGRAP;GHPG;RA","Chat":"Test.txt"} is not a valid json, that's why you encounter that error,
The other way around, you could parse
JSON.parse('{"Code":"\'GAHGAaphgAP:gjpaGHAHAG{AaGRAP;GHPG;RA","Chat":"Test.txt"}')
Try
var uri = "http://localhost:1337/%7B%22Code%22:%22%5C'GAHGAaphgAP:gjpaGHAHAG%7BAaGRAP;GHPG;RA%22,%22Chat%22:%22Test.txt%22%7D";

Error: Number of columns is inconsistent on line 5 - While parsing CSV

I am attempting to parse a CSV file that uses tabs as column delimiter. I am getting the error below:
Error: Number of columns is inconsistent on line 5
at Parser.__push (/Users/mesamhaider/Desktop/workspace/Order_CSV_Parsing_Tool/node_modules/csv-parse/lib/index.js:248:14)
at Parser.__write (/Users/mesamhaider/Desktop/workspace/Order_CSV_Parsing_Tool/node_modules/csv-parse/lib/index.js:469:20)
at Parser._transform (/Users/mesamhaider/Desktop/workspace/Order_CSV_Parsing_Tool/node_modules/csv-parse/lib/index.js:182:14)
at Parser.Transform._read (_stream_transform.js:190:10)
at Parser.Transform._write (_stream_transform.js:178:12)
at doWrite (_stream_writable.js:371:12)
at writeOrBuffer (_stream_writable.js:357:5)
at Parser.Writable.write (_stream_writable.js:274:11)
at ReadStream.ondata (_stream_readable.js:626:20)
at emitOne (events.js:115:13)
The code that I am using is shown below:
const fs = require('fs');
const parse = require('csv-parse');
fs.createReadStream('../in/*.csv')
.pipe(parse({delimiter : ' '}))
.on('data', function(row){
console.log(row)
})
The code will do much more than logging it to the console but for example's purpose, I put it this way. Also - once I parse this would it be possible to input each column inside of a SQL insert statement?
Here is an example code for you. Please install should node module for this code to run.
You create the parser with parser() function
Write inside it with write() function
retrieve data with on.finish().
const fs = require('fs');
const parse = require('csv-parse');
require("should");
var myReadStream = fs.createReadStream('../in/*.csv');
var parser = parse({delimiter: ':'});
parser.write(myReadStream);
parser.on('error', function(err){
console.log(err.message);
});
parser.on('finish', function(){
output.should.eql([Bunch of arrays here from the file]);
});
See here for more information.

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

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

Why is bot undefined?

I am developing a Discord bot using the Discord.js API. So far so good, but I thought it would be nice to have the newest post on a relevant subreddit be announced in the chat by my bot every couple of minutes. Now I have managed to make the script pull the relevant data out of the Reddit JSON API, but this error is thrown:
TypeError: Cannot read property 'sendMessage' of undefined
at /data/app/app.js:810:7
at Array.forEach (native)
at IncomingMessage.<anonymous> (/data/app/app.js:808:36)
at emitNone (events.js:72:20)
at IncomingMessage.emit (events.js:166:7)
at endReadableNT (_stream_readable.js:913:12)
at nextTickCallbackWith2Args (node.js:442:9)
at process._tickCallback (node.js:356:17)
/data/app/app.js:810
bot.sendMessage(channel,"https://www.reddit.com" + child.data.permalink);
This is my code:
var Discord = require("discord.js");
var bot = new Discord.Client();
var redditSubModule = "pics";
function getRedditPosts(bot, msg) {
var url = "http://www.reddit.com/r/" + redditSubModule + "/new/.json?limit=2";
var request = http.get(url, function(response) {
var json = "";
response.on("data", function(chunk) {
json += chunk;
});
response.on("end", function() {
var redditResponse = JSON.parse(json);
redditResponse.data.children.forEach(function(child) {
console.log("https://www.reddit.com" + child.data.permalink);
bot.sendMessage(msg.channel,"https://www.reddit.com" + child.data.permalink);
});
});
});
request.on("error", function(err) {
console.log(err);
});
setTimeout(getRedditPosts, 60000);
}
getRedditPosts();
Why is bot undefined?
It seems like you're expecting getRedditPosts to be called with attributes (bot, msg), but you are calling it with no attributes getRedditPosts();
So basically you are passing undefined as the bot variable.
undefined has no functions on it and you are trying to call sendMessage
and that is the meaning of Cannot read property 'sendMessage' of undefined
You will also need to call the function getRedditPosts() when a user runs a command. Something like:
bot.on('message', (msg)=>{
if(message.content.toLowerCase().startsWith("!redditcommand")) {
getRedditPosts(msg.client, msg)
}
}
At the end of your code in place of the getRedditPosts(); should do the trick.

Reference error is not thrown from MongoDB callback

Introduction
All people know that if we call undefined.test we will receive the following error (same for both: NodeJS and Javascript):
$ node
> undefined.test
TypeError: Cannot read property 'test' of undefined
at repl:1:11
at REPLServer.self.eval (repl.js:110:21)
at Interface.<anonymous> (repl.js:239:12)
at Interface.EventEmitter.emit (events.js:95:17)
at Interface._onLine (readline.js:202:10)
at Interface._line (readline.js:531:8)
at Interface._ttyWrite (readline.js:760:14)
at ReadStream.onkeypress (readline.js:99:10)
at ReadStream.EventEmitter.emit (events.js:98:17)
at emitKey (readline.js:1095:12)
That's correct!
How did I find the problem?
Passed week I wasted about 30 minutes in debugging the following problem: A script was stopping accidentally and no error was thrown.
I had the urls variable that was supposed to be an object:
var urls = settings.urls || {};
Then in next lines I needed to get shop key of urls that was a string:
var shop = urls.shop || "/";
I started adding console.log to find the values of variables:
console.log(urls); // undefined
var shop = urls.shop || "/";
console.log("Passed"); // This isn't run.
The problem in my script was that I was redefining a new urls variable that was making the urls undefined, but the question is: why cannot read property "shop" of undefined didn't appear here? Because urls was really undefined.
We know that the following is happening in both: NodeJS and Javascript:
var a = 10;
foo(function () {
console.log(a); // undefined
var a = 10;
});
function foo(callback) { callback(); }
The question
After debugging the problem I found that this problem comes from Mongo: inside of Mongo callbacks if we call undefined.something we DON'T get the error.
I've created a small script that demonstrates this:
var mongo = require("mongodb");
// Mongo server
var server = mongo.Server("127.0.0.1", 27017);
var db = new mongo.Db("test", server, { safe: true });
console.log("> START");
// Open database
console.log("Opening database.");
db.open(function(err, db) {
if (err) { return console.log("Cannot open database."); }
// get collection
console.log("No error. Opening collection.");
db.collection("col_one", function(err, collection) {
if(err) { return console.log(err) }
// do something with the collection
console.log("No error. Finding all items from collection.");
collection.find().toArray(function(err, items) {
if(err) { return console.log(err) }
console.log("No error. Items: ", items);
console.log("The following line is: undefined.shop." +
"It will stop the process.");
console.log(undefined.test); // THE ERROR DOES NOT APPEAR!
console.log("> STOP"); // this message doesn't appear.
});
});
});
My questions are:
Why the error doesn't appear? Which is the reason? (It would be great to debug together the MongoDB source code to find it.)
Why the process is stopped when calling undefined.something?
How can be this solved?
I've created a Github repository where you can download my small application that demonstrates the issue.
Interesting:
If we add a try {} catch (e) {} statement we find the error and the process continue showing the STOP message.
try {
console.log(undefined.test);
} catch (e) {
console.log(e);
}
LOGS:
> START
Opening database.
No error. Opening collection.
No error. Finding all items from collection.
No error. Items: []
The following line is: undefined.shop. It will stop the process.
[TypeError: Cannot read property 'test' of undefined]
> STOP
Looking on github.com at node-mongodb-native driver issues, you will notice that issue is solved in 1.3.18 version. But, I tested it and it does not work as expected.

Categories