How to validate a JSON String JQuery [duplicate] - javascript

This question already has answers here:
AJAX: Check if a string is JSON?
(8 answers)
Closed 9 years ago.
I tried that:
var c = $.parseJSON(something here)
and I control that:
c === undefined
This works however it throws error while trying to parse an invalid JSON string. I don't want it throw that error.
Any advices?

It's generally considered bad practice to suppress/ignore errors, instead why not use a try-catch block to capture the exception and do something with it:
try {
var c = $.parseJSON(something here);
}
catch (err) {
// Do something about the exception here
}
If you really don't need to do anything about the exception at least put a comment to that effect in your try-catch block, it'll make your code more readable when you come back to it later.

Related

What does the [whatever]:[number] construct mean in the developer console? [duplicate]

This question already has answers here:
What does ':' (colon) do in JavaScript?
(11 answers)
Closed 9 months ago.
When I was using the developer console in the browser, I accidentally entered a construction like whatewer:42
The console in response output a number after the colon. I don't understand why such a construction is needed. If you use it anywhere else, you get an error.
If you use it anywhere else, you get an error.
No, you don't. It's a labeled statement.
function test() {
whatever: 42;
console.log('No error');
}
test();

How do I prevent TypeError blank is undefined? [duplicate]

This question already has answers here:
Test for existence of nested JavaScript object key
(64 answers)
Closed 3 years ago.
Is there an easier way to check if a variable is defined or not in JavaScript when the target is deep within an object?
For example.
// Lets assume this:
response = {
status: "simple-message"
}
// running this:
if (response.data.variable_to_check !== undefined) console.log('undefined');
// will result in this:
> TypeError: response.data is undefined
In PHP I can run the equivalent check:
if (!($response->data->variable_to_check ?? false)) die("Handled Undefined Error");
// will result in this:
> Handled Undefined Error
I know I can iterate manually by checking each item starting with the root to see if it's defined, but that seems tedious. That and wrapping everything in a try/catch.
Is there a cleaner / faster / smarter way to do this?
Use
try{
if(response.data.variable_to_check!==undefined){
console.log("undefined");
}
}
catch(err){console.log(err.message)}

replacing a promise string not executed [duplicate]

This question already has answers here:
JS replace not working on string [duplicate]
(2 answers)
I want to replace '\' with '/'
(1 answer)
Closed 4 years ago.
I'm trying to replace all instances of 'formattedTime' in a massive string.
Here's my code
googleTrends.interestOverTime({keyword: selectedTopic})
.then((results) => {
results.replace(/formattedTime/g, 'no what the heck');
console.log(results);
})
.catch((err) => {
console.error('Oh no there was an error', err);
});
I am not receiving any errors however nothing is happening inside my console.
I even tried replacing a single line string but none of it will work. It might be because of the promise I'm receiving?
I am relatively new to RegEx so I thought maybe that was an issue but it doesn't seem to be.
Strig.prototype.replace does not mutate the string. Strings are immutable. It will return a new string.

Why does If statement throw an undefined error when I am checking if its undefined? [duplicate]

This question already has answers here:
Access Javascript nested objects safely
(14 answers)
Closed 4 years ago.
Why does my else if statement cause the parser to throw an undefined error? I know that it is undefined which is why I am checking, I want it to hit the else block in this case, because this function is used in mutiple places the data that is being passed in is not always the same. So I am trying to check which type of data is being passed in.
if(icon){
dv.find(".mobCol>.image").html(generateIcon(icon));
}
else if(location[0].properties !== undefined){
dv.find(".mobCol>.image").html(generateIcon(location[0].properties.image));
data = location[0];
}
else{
dv.find(".mobCol>.image").html(generateIcon(location.features[0].properties.image));
data = location.features[0];
}
Because location[0] is undefined. It's a bit odd, but your check should be:
if( location[0] && location[0].properties){ /* .. */}
I've omitted the ===undefined, thats not needed. It tests if it is something is thruthy or falsey
This is a common way to check variables in JS.

isJSON in javascript, without try/catch [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to check if a string is a valid JSON string in JavaScript without using Try/Catch
The question was already asked here : How to check if a string is a valid JSON string in JavaScript without using Try/Catch. No valid answer was given, even the validated one wasn't answering the question.
So it seems the only way to not doing this using try/catches is via regexps; the regexp given in one of the answers was only validating against eval, so a simple string like "2001-05-06" would pass the regexp, even though it's not JSON.
So has anyone a good regexp to validate against a well formed JSON string ?
Using a regex instead of a try/catch is replacing a correct solution with a non working hack.
The link you give suggests to change the JSON parsing code that you can modify to not throw an exception. I would suggest replacing in json_parse.js the following code
error = function (m) {
// Call error when something is wrong.
throw {
name: 'SyntaxError',
message: m,
at: at,
text: text
};
},
by the call of a callback you would provide.
But to be frank, my most reasonable suggestion would be to use try/catch. That's the best tool you have here. Note that my JSON.parse modification "suggestion" supposes to manage the break from all loops/recursions, which is precisely what an exceptions does.
from link try this
var jsonData = '{"1":"test"}';
if (/^[\],:{}\s]*$/.test(jsonData.replace(/\\["\\\/bfnrtu]/g, '#'). replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']'). replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
alert('ok');
}else{
alert('no');
}

Categories