Check if json object is undefined in Node.js - javascript

I'm getting this error "TypeError: Cannot read property '0' of undefined" when I want to extract a data from JSON file.
However, the data I want to extract is not available every time I request a JSON file, therefore, I'm getting this error which makes my Node.js Application to crash every time I'm getting this error.

simply check if it exists or not:
if (json && json['Name'] && json['Name']['Nationality']) {
data = json['Name']['Nationality'][0];
} else {
// no data, do whatever error handling you want here
}

A solution for this sort of problem is using try-catch:
try {
data = json['Name']['Nationality'][0];
} catch (error) {
data = "Sorry no data found"
}
The try function is going to run the code if it did find any error it will pass it to catch.

Related

how to fetch data from key value pair in vuejs

I am using rails on the backend and vue.js on the front end. I am trying to print the error in case there is any. Under the .catch I have got the error as below but cannot fetch the message from it. Kindly help me resolve it.
.catch(function (error) {
debugger
});
In the console, if I try error.response.data.error this returns '{:message=>"Amount is less than the minimum value"}' I am not able to figure out how I can fetch just the message.
Error Answer
Your baclend is not serializing object correctly. So message is a part of a string instead of JSON property. If you don't want to change that you can use
const message = error.response.data.error.substring(
str.indexOf('"') + 1,
str.lastIndexOf('"')
);

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.

JSON - extract call from REST call

I am using a third party database which has a rest API. When I make a call I get an error back (which I am expecting in my case):
transaction.commit(function(err) {
if (err){
var par = JSON.parse(err); \\ returns error: SyntaxError: Unexpected token E in JSON at position 0
console.log(JSON.stringify(err));
console.log(err);
console.log('' + err);
//First console.log return: {"code":409,"metadata":{"_internal_repr":{}}}
//Second console.log return: { Error: entity already exists: app: "s~myapp"<br/>path <<br/> Element {<br/> type: "v"<br/> name: "bob#gmail.com"<br/> }<br/>><br/>
//Third console.log returns: Error: entity already exists: app: "s~myapp"<br/>path <<br/> Element {<br/> type: "v"<br/> name: "bob#gmail.com"<br/> }<br/>><br/>
}
{);
I need to extract the error field and the type field. I have tried to parse the JSON and then go par.error or par.type to get the variables, but I can't parse the object because I get an error.
You're apparently having an Error object, that has a message property to extract the message string.
Hence use
err.message
to obtain it.
References:
Error.prototype.message
Error
Based on your results, it seems that the err parameter that you're getting is already an object and not a JSON string, so you don't need to parse it at all.
You should be able to get err.code without problem.
You did mention that you need to get the error type -- but that seems to not be available in that object at all (and that's why you'd get undefined while you tried it.
However, by using err.Error you should be able to get the error string.
If you're unsure of what data the object has, you can try the following:
Execute console.dir(err) -- this should give you a good understanding of what the err object contains.
Just debug up to that point and look around in the err object.
(Best option) Check the platform's / libraries API documentation, it should tell you what error information it returns so you can use exactly that.

Duck Typing with JSON object - try/except?

In AngularJS, I have a api request that goes out and a JSON is returned. The JSON is stored as object data and I use data.Automation.Status to check the string in Status.
There are a few JSON errors that could a rise(after http 200 success with the json returned successfully):
The entire JSON could be returned a blank string ""
data JSON object could exist, but Automation JSON object could be undefined
Property Status of object Automation could be undefined or a blank string
Coming from python, all these possible situations could easily be handled in a try/except block.
Try:
do something with JSON
except (blah, blah)
don't error out because JSON object is broken, but do this instead
I see angular has $errorHandler service that can be modified with custom handlers. But I am not sure if this can be used in the same manner of duck typing that I am looking for.
How could I go about duck typing in AngularJS? Specifically, for the JSON object error scenerios mentioned in the list above?
How I am using data.Automation.Status at the moment:
if (iteration < Configuration.CHECK_ITERATIONS && data.Automation.Status !== "FAILED") {
iteration++;
return $timeout((function() {
return newStatusEvent(eventId, url, deferred, iteration);
}), Configuration.TIME_ITERATION);
} else {
err = data.Automation.StatusDescription;
return deferred.reject(err);
}
Here's how I came to a solution for the same problem.
It keeps it minimal, and all of the tests are grouped in one block.
$http.get('/endpoint1').success(function(res) {
try {
// test response before proceeding
if (JSON.stringify(res).length === 0) throw 'Empty JSON Response!';
if (!res.hasOwnProperty('Automation')) throw 'Automation object is undefined!';
if (!res.Automation.hasOwnProperty('Status') || res.Automation.Status !== 'SUCCESS')
throw 'Automation Status Failed!';
} catch (err) {
// handle your error here
console.error('Error in response from endpoint1: ' + err);
}
// if your assertions are correct you can continue your program
});
The best way that comes to mind to handle this situation would be using $parse since it handles undefined very well. You could do something like this:
$http.get('/endpoint1').success(function(res) {
try {
// test response before proceeding
if (angular.isUndefined($parse('Automation.Status')(res))) {
throw 'Automation Status Failed!';
}
} catch (err) {
// handle your error here
console.error('Error in response from endpoint1: ' + err);
}
// if your assertions are correct you can continue your program
});
You can see in this plunker how $parse handles your scenarios.
Depending on how complicated you want to get. If you want to use coffeescript, there's a nice ? operator: json.knownToExist.maybeExists?.maybeAlsoExists?() will never error out, and will only call maybeAlsoExists if it exists.
Otherwise, you could use typeof checks:
foo = {a: 1, b: 2}
typeof foo === 'object'
typeof foo.bar === 'undefined'
I'm under the impression that try/catch blocks in javascript are relatively expensive. So you probably want to test the json manually, especially if the different return values from your service are what you'd call 'normal' responses. Exceptions, IMO, should be used for exceptional occurrences, and not sanity checking.

Having troubles with getting data from Meteor collection

Can someone explain this thing to me: if I'm getting data from a collection in browser's console, it works fine, but at the same time when a template (which uses the same collection) is being rendered it throws an exception as the query result is empty. What am I doing wrong?
Hubs = new Meteor.Collection("hubs");
Meteor.subscribe("hubs");
Template.thread.posts = function() {
var hubName = 'foo',
thread = Session.get("currentThread"),
hub = Hubs.find({ name: hubName }).fetch()[0];
//throws: "Uncaught TypeError: Cannot read property 'threads' of undefined "
return hub.threads[thread].posts;
}
//this being executed in browser's console yeilds an object:
Hubs.find({name: 'foo'}).fetch()[0]
Other templates that use the same collection work fine, though
When Meteor initially loads on the browser it wont yet have the data from the collections from the server.
It takes a very short amount of time for them to be available. So you just need to handle the case where there is no result provided. When the data arrives reactivity should update all your templates with the new data.
You can use something like:
hub = Hubs.findOne({ name: hubName })
if(hub) return hub.threads[thread].posts;
findOne is a shorter version of find().fetch[0]. So if there isn't a result i.e null nothing is returned and .threads wont be read so there wouldn't be an exception.

Categories

Resources