How do I fix this Unexpected token error? - javascript

Getting an error and I don't know why. Any idea?
Unexpected token / in JSON at position 233
I have found a few possible fixes and implemented them but they have not worked either.
This is the code:
const v2_ABIs = require("./Uniswap_V2_ABIs.json");
const v2abi = JSON.parse(v2_ABIs);
v2abi = v2abi.trim();
console.log(v2abi);

I had a read through the comments. If removing JSON.parse stopped causing the error. That means the JSON you where using contained something that caused a js exception when trying to parse it. If you can share the JSON I can pinpoint the exact issue, but if you don't actually need to parse it then its no problem.

Related

Cannot read properties of undefined (reading '0') - ( empty error JSON response with postman)

so i'm working with Joi for validation, and i've encountered this error when trying to post with postman.
i'm follwing a tutorial, i tried to write it differently, but still have the same issue.
i'm trying to access the error message. ( first selecting the error, then the details, then the message )
in the tutorial, it looks like this
res.send(error.details[0].message)
i can see the error, but once i select details, the response is empty.
let me know if you need anything else.
Thank you in advance.
The Lord be with you and save you all, your families and friends :)
It seems like error does not have a property called details. That's why error.details is undefined. Thus, when trying to access the element of the first index of the value undefined you'll get an error.
To fix:
Make sure the error object contains a property details of type Array
If error.details will depend on other code blocks (sometimes it is defined, sometimes it isn't), you can add a ternary expression to tell your code what to in case error.details is indeed undefined.
Example:
err.details ? res.send(error.details[0].message) : res.send("error")
Which translates to
if (err.details) { // if defined
res.send(error.details[0].message) // Send the message from the error
} else {
res.send("error") // Send a general message
}

JSON.parse() Error SyntaxError: Unexpected token < in JSON at position 0

I'm following along this udemy course on fullstack webdev. Fun so far until I hit this snag.
This lesson is about API and JSON and we are making a "Sign Up" email service using Mailchimp API.
I have the following constant:
And when using nodemon this is the error I get:
That app.js 43:24 points to the:
console.log(JSON.parse(data)); line.
I've checked my api key and that's correct, the options and url are set correctly.
I've been scrathing my head over this one.
Any ideas where to begin troubleshooting?
Can you do console.log(data) once and validate that data is not undefined.
If we do JSON.parse(undefined), we get the same error as the one you are getting. You can put an if block to see if data is not undefined and then selectively parse.
if(data != null){
console.log(JSON.Parse(data);
}
Check the data.
You don't need of JSON.parse(data) it because the data is already in JSON.

Uncaught SyntaxError: Unexpected token u in JSON at position 0

Only at the checkout and on individual product pages I am getting the following error in the console log:
VM35594:1 Uncaught SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse (<anonymous>)
at run (layout.min.js:9)
at app.min.js:1
at main.min.js:2
at Object.execCb (require.min.js:112)
at Module.check (require.min.js:56)
at Module.<anonymous> (require.min.js:72)
at require.min.js:11
at require.min.js:74
at each (require.min.js:3)
I am using a one page checkout extension, but when I disable that the error still shows. I thought it might had something to do with the reviews on the product page (as I moved the reviews out of the tabs), but undoing that change didn't fix the error on the product pages.
Try this in the console:
JSON.parse(undefined)
Here is what you will get:
Uncaught SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse (<anonymous>)
at <anonymous>:1:6
In other words, your app is attempting to parse undefined, which is not valid JSON.
There are two common causes for this. The first is that you may be referencing a non-existent property (or even a non-existent variable if not in strict mode).
window.foobar = '{"some":"data"}';
JSON.parse(window.foobarn) // oops, misspelled!
The second common cause is failure to receive the JSON in the first place, which could be caused by client side scripts that ignore errors and send a request when they shouldn't.
Make sure both your server-side and client-side scripts are running in strict mode and lint them using ESLint. This will give you pretty good confidence that there are no typos.
As #Seth Holladay #MinusFour commented, you are parsing an undefined variable.
Try adding an if condition before doing the parse.
if (typeof test1 !== 'undefined') {
test2 = JSON.parse(test1);
}
Note: This is just a check for undefined case. Any other parsing issues still need to be handled.
localStorage.clear()
That'll clear the stored data. Then refresh and things should start to work.
Your app is attempting to parse the undefined JSON web token. Such malfunction may occur due to the wrong usage of the local storage. Try to clear your local storage.
Example for Google Chrome:
F12
Application
Local Storage
Clear All
For me, that happened because I had an empty component in my page -
<script type="text/x-magento-init">
{
".page.messages": {
"Magento_Ui/js/core/app": []
}
}
Deleting this piece of code resolved the issue.
This is due to the interfering messages that come on to the page. There are multiple frames on the page which communicate with the page using window message event and object. few of them can be third party services like cookieq for managing cookies, or may be cartwire an e-com integration service.
You need to handle the onmessage event to check from where the messages are coming, and then parse the JSON accordingly.
I faced a similar problem, where one of the integration was passing a JSON object and other was passing a string starting with u
If you get Uncaught SyntaxError: Unexpected token u in JSON at position 0 then you could do the following quick checks:
jsObj = JSON.parse(data)
data - check the data is undefined or not
data - check the data is a valid JSON string or not
data - check the data is corrupted by unwanted whitespace or not
data = data.trim(); // remove the unwanted whitespace
jsObj = JSON.parse(data);
data - check the received data uses the correct encoding format('utf8', 'utf16le', 'ucs2') or not
fs.readFile(file, 'utf8', function(err, data) { ... });
fs.readFile(file, 'utf16le', function(err, data) { ... }); // le - little endian
fs.readFile(file, 'ucs2', function(err, data) { ... }); // kind of 'utf16le'
I had this issue for 2 days, let me show you how I fixed it.
This was how the code looked when I was getting the error:
request.onload = function() {
// This is where we begin accessing the Json
let data = JSON.parse(this.response);
console.log(data)
}
This is what I changed to get the result I wanted:
request.onload = function() {
// This is where we begin accessing the Json
let data = JSON.parse(this.responseText);
console.log(data)
}
So all I really did was change
this.response to this.responseText.

How to return a map function that has hyphenated field in mongoDB

I was working with Meteor and mongoDB and I've run into a problem. My schema has a hyphenated name and I'm unable to retrieve it's value from map. How do I circumvent this?
My mongoDB collection has a field named:
"loopback-mode" : "no-loopback",
My query being:
db.collection.find({templateName:"someTemplate"},{"loopback-mode":1,_id:0}).map(function(c) {return c.loopback-mode;})[0];
c.loopback-mode seems to be causing the of problem.
I get the error saying:
SyntaxError: Unexpected token -
I've tried c[loopback-mode], c["loopback-mode"], c."loopback-mode" etc,
but to no success. What's the right way to do this?
The way to go should be
....map(function(c) { return c['loopback-mode']; })...
I just tested it - see the GIF below
As you mentioned that you tested that already, please try again and if it still does not work then please share the error (if any). The initial syntax error should be gone for sure.

Node.js JSON parsing error

I am attempting to make a Facebook application with node.js, however I'm having trouble in checking signed requests. Every time I make a request, the program throws a SyntaxError: Unexpected token ILLEGAL as such:
undefined:1
":"721599476"}
^^
SyntaxError: Unexpected token ILLEGAL
The culprit function is below:
function parse_signed_request(signed_request, secret) {
encoded_data = signed_request.split('.',2);
// decode the data
sig = encoded_data[0];
json = base64url.decode(encoded_data[1]);
data = JSON.parse(json); // ERROR Occurs Here!
// check algorithm - not relevant to error
if (!data.algorithm || data.algorithm.toUpperCase() != 'HMAC-SHA256') {
console.error('Unknown algorithm. Expected HMAC-SHA256');
return null;
}
// check sig - not relevant to error
expected_sig = crypto.createHmac('sha256',secret).update(encoded_data[1]).digest('base64').replace(/\+/g,'-').replace(/\//g,'_').replace('=','');
if (sig !== expected_sig) {
console.error('Bad signed JSON Signature!');
return null;
}
return data;
}
Just for testing, a valid signed_request would be
WGvK-mUKB_Utg0l8gSPvf6smzacp46977pTtcRx0puE.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImV4cGlyZXMiOjEyOTI4MjEyMDAsImlzc3VlZF9hdCI6MTI5MjgxNDgyMCwib2F1dGhfdG9rZW4iOiIxNTI1NDk2ODQ3NzczMDJ8Mi5ZV2NxV2k2T0k0U0h4Y2JwTWJRaDdBX18uMzYwMC4xMjkyODIxMjAwLTcyMTU5OTQ3NnxQaDRmb2t6S1IyamozQWlxVldqNXp2cTBmeFEiLCJ1c2VyIjp7ImxvY2FsZSI6ImVuX0dCIiwiY291bnRyeSI6ImF1In0sInVzZXJfaWQiOiI3MjE1OTk0NzYifQ
Why am I getting this error when it is valid JSON and simply using a static string of JSON will work fine, and are there any tips to fix this?
Thanks.
Ok, after a bit of testing I've fixed the problem myself, sorry for the wasted question.
Something in my base64 library wasn't decoding the string properly (although it appeared to be - so it must have been a non-displaying character or padding, etc.)
I've changed over to https://github.com/kriszyp/commonjs-utils/blob/master/lib/base64.js which suits my purposes, although needed to be modified to support base64url decoding rather than normal base64, and it seems to work fine now.

Categories

Resources