I am getting an error that says SyntaxError: Unexpected token a in JSON at position 0
and I cannot find any information on what "a" means. I know that the JSON is not undefined.
Can anyone help me understand what is causing this error?
Here is the code block that is causing the error:
let db_creds = await getDBCredentials();
console.log(db_creds)
const pool = new Pool(JSON.parse(db_creds['SecretString']));
console.log(pool)
Unexpected Token < in JSON at Position 0. From time to time when working with JSON data, you might stumble into errors regarding JSON formatting. For instance, if you try to parse a malformed JSON with the JSON. ... json() method on the fetch object, it can result in a JavaScript exception being thrown.
What Is JSON and How to Handle an “Unexpected Token” Error
Well for me it was because the port was already in use and it must be sending HTML, you can try killing the port by running the below command in cmd(admin mode)
taskkill /F /IM node.exe
Related
Me and others are experiencing this error: SyntaxError: Unexpected token } in JSON at position 24 at JSON.parse (<anonymous>) while following this tutorial on JSON Web Tokens (LINK: https://www.youtube.com/watch?v=mbsmsi7l3r4&t=34s, around minute: 10:00)
The error appears during this POST request:
Content-Type: application/json
{
"username": "Kyle",
}
You can find the full code up to that point here:
https://github.com/emanuelefavero/json-web-tokens
There are 3 main files to watch for:
server.js
.env (I left the .env file in the github repository)
request.rest (I used this file to make POST request but you can use POSTMAN or other methods)
The error seems to be in server.js, specifically in the express-JWT method:
app.post('/login', (req, res) => {
// Authenticate User
// Create json web token
const username = req.body.username
const user = { name: username }
const accessToken = jwt.sign(user, process.env.ACCESS_TOKEN_SECRET)
console.log(accessToken)
res.json({ accessToken: accessToken })
})
The GET request is working fine.
While I'm trying to fix this error I'll still respond to any questions and provide project details if needed. Thank you.
Full Error Message:
SyntaxError: Unexpected token } in JSON at position 24
at JSON.parse (<anonymous>)
at parse (/Users/arch0n/Desktop/JWT/json-web-token/node_modules/body-parser/lib/types/json.js:89:19)
at /Users/arch0n/Desktop/JWT/json-web-token/node_modules/body-parser/lib/read.js:128:18
at AsyncResource.runInAsyncScope (node:async_hooks:199:9)
at invokeCallback (/Users/arch0n/Desktop/JWT/json-web-token/node_modules/raw-body/index.js:231:16)
at done (/Users/arch0n/Desktop/JWT/json-web-token/node_modules/raw-body/index.js:220:7)
at IncomingMessage.onEnd (/Users/arch0n/Desktop/JWT/json-web-token/node_modules/raw-body/index.js:280:7)
at IncomingMessage.emit (node:events:402:35)
at endReadableNT (node:internal/streams/readable:1343:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21)
It appears the issue lies in the request you're making. You have a trailing comma in the JSON that you are sending in your request.
If you are new to using JSON & JavaScript, just try to remember that JavaScript objects !== JSON.
In JS Objects, you can have trailing commas. However, in JSON it will cause issues.
Prevent server from crashing.
I am testing an API with Postman where I am expecting a number with or without decimal places.
But it happens that at the time of testing if I enter a sign like this in Postman: " ) " the server crashes automatically and it seems that it does not reach my validator.
Postman:
{
"concept": "Text",
"incomeAmount": 1)0000,
"expenseAmount": 89,
"description":"Text"
}
Failed response:
SyntaxError: Unexpected token ) in JSON at position 73
at JSON.parse ()
at parse (C:\project\node_modules\body-parser\lib\types\json.js:89:19)
at C:\project\node_modules\body-parser\lib\read.js:121:18
at invokeCallback (C:\project\node_modules\raw-body\index.js:224:16)
at done (C:\project\node_modules\raw-body\index.js:213:7)
at IncomingMessage.onEnd (C:\project\node_modules\raw-body\index.js:273:7)
at IncomingMessage.emit (node:events:402:35)
at IncomingMessage.emit (node:domain:475:12)
at endReadableNT (node:internal/streams/readable:1343:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21)
I am using express validator like this:
router.post('/new-income',
[
check('incomeAmount', 'El Monto del Ingreso debe ser Númerico').isNumeric().not().isEmpty(),
check('expenseAmount', 'El Monto del Egreso debe ser Númerico').isNumeric().optional({ checkFalsy: true }),
],
validation,
newItem
);
And in the controller, I use Regex to verify that it is a positive number without symbols, but apparently neither the request nor the route arrives.
const regAmount = new RegExp('^[+]?([1-9][0-9]*(?:[\.][0-9]*)?|0*\.0*[1-9][0-9]*)(?:[eE][+-][0-9]+)?$');
if (!regAmount.test(incomeAmount)) {
return res.json ( {
'msg': 'Only positive numbers without signs are allowed'
} );
}
Thanks for your help!
With this much information I can only assume that you are using some kind of json middleware that parse the incoming data.
Unfortunately, the data you sent via postman is not in a valid json format. Ironically enough, only valid number are accepted as value without the need of quotation mark (excluding array and object).
A solution maybe to send the data as pure text to your api and then run in through your validation before converting it into a number.
You can verify the json format yourself here: https://jsonformatter.curiousconcept.com/
This is expected. You're sending illegal JSON so your JSON parsing middleware gets an exception. To catch/handle this error, you need to either install custom middleware that catches the error in the middleware or catch the error from the existing JSON parser in the Express error handler by installing your own Express error handler.
Also, if you're using the express.json() middleware, it has a verify callback option that you can pre-check the JSON if you want, but frankly, it's probably easier to just have an Express error handler and get the error there.
Error: SyntaxError: Unexpected token o in JSON at position 1
Code:
collection3.find({username: req.body.accept}).toArray((error, user) => {
a = JSON.parse(user)
})
This is happening because the user variable is an object. The JSON.parse function expects to be passed a string, not an object. If you pass an object, you will get the 'Unexpected token o' error message. You can produce this error message directly by running the following code:
JSON.parse({})
The working equivalent of the above code is:
JSON.parse('{}')
I want to livestream telemetry data formatted in JSON from a websocket to a browser using javascript.
A websocket is created on a server X.X.X.X using native c and the websocketd wrapper on port 8080. A client (IP: Y.Y.Y.Y) shall connect to the very same server via https on port 80 (https://X.X.X.X:80) and shall receive javascript code which tells it to grab livestream data from the websocket (ws://X.X.X.X:8080) and refresh some values on the website with the values from this stream.
The data can exemplarily look like this:
{
"name of system": {
"RSSI": {
"rssi": "0",
"adc1": "0.00",
"adc2": "0.00",
"rxBatt": "0.00",
"swr": "0"
},
"ASS": {
"airspeed": "0.00"
}
}
}
{...}
and so on...
This frame shall be repeated e.g. in a 500ms interval and is sent with no whitespaces nor newline characters.
I tried parsing this already with JSON.parse() but my browser console returns following error: "Uncaught SyntaxError: Unexpected token *" or "Unexpected token {". Is this because of wrongly implemented JSON code, although I checked it several times?
My question is now: Is JSON.parse really capable of livestreaming? If not, are there libraries which are, or am I better off with a completely new solution?
Best regards
If the JSON parser is encountering an asterisk, as suggested by Unexpected token *, then your JSON is malformed, as that's not a valid character in JSON (outside of a string).
I'd recommend examining the message being received and visually check that it's valid JSON. Something like:
webSocket.onmessage = function(event) {
console.log(event.data);
}
Then, you can check your browser's developer console (usually Cmd-Shift-I on a Mac or F12 elsewhere) to see what you're actually receiving.
I have a JavaScript application which is running in Node.js environment and communicates to its clients ( also in JavaScript ) using a ZeroMQ. The messages come on the server in JSON format.
The application code throws it out
Node.js SyntaxError: Unexpected token in JSON at position 0
when it is parsed using JSON.parse(). I'm unable to figure out the issue. I've verified the JSON using http://jsonlint.com
Any help with JSON.parse() is welcome.
Edited:01/10/17, 15:33
Here are the client and server JavaScript code files. You'll need to create the .js files, can't post such a big code.
The JSON data file is also provided.
You'll need to launch the server.js and client.js and then the server console will print out the exception for unrecognized character.
https://www.4shared.com/folder/6VFJqrgU/javascript.html
Stackoverflow imposes link posting restrictions so had to post one link with all the files.
Just for info, I'm a C++ programmer, so don't bother about the code formatting or style of programming. I had to do it for a project need.
Edit 02/10/17, 11:50: Well it turns out that it is the JSON.parse() method which is unable to parse the json. But, I added a .trim() call to the args[1].toString() and the error has moved downstream. Unexpected token o in JSON at position 10. I don't understand what is wrong!!
Edit 04/10/17: Here is the minimal code.
var fs = require('fs');
try
{
var event = fs.readFileSync('demoReport.json', 'utf8');
console.log(event);
var eventObj = JSON.parse(event);
var reportName = event["ReportName"];
var reportData = event["ReportData"];
console.log(reportData);
}
catch(error)
{
console.log("JSON parsing failed: " + error);
}
This is the json:
{"EventName":"ReportGenEvent","TemplateFileNameLocation":"File location","ReportFormat":".pdf","ReportName":"TestReport","ReportLocation":"report location","Locale":"French","ReportData":{"dateTime":"2017-09-29T00:05:22.824Z","streamName":"","measurementTime":"2017-04-01T01:13:25.000Z","durationSeconds":0.0,"outOfBand":false,"notFinal":false,"newMeasurement":false,"savedFileName":"","measurementType":"Unknown","analysisElapsedSeconds":1.3462,"analysisElapsedCPUSecs":0.0624004,"geometryID":"GEOM","geometryDescription":"","measurementUUID":"6060c80f-007c-4992-88f8-55e2200d99b7","backgroundUUID":"","measurementWorkflowID":"Measurement","instrumentProperties":{"classCode":8,"description":"","manufacturer":"","model":"","properties":"locationName=Home latitude=25 longitude=20 elevation=30","serialNumber":"product/1","versionInformation":"=V1.0"}}}
Thanks.