isJSON in javascript, without try/catch [duplicate] - javascript

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

Related

Turn a string into function in JS [duplicate]

This question already has answers here:
How to execute a JavaScript function when I have its name as a string
(36 answers)
Closed 2 years ago.
My problem is simple and I couldn't find the proper answer in this forum. My bad...
I want to do that :
const dataReceived = foo;
foo(state);
How can I do that?
I read it is better to avoid eval, and I couldn't get success with new Function.
Thanks for your help!
EDIT
Thanks for your answers.
I work with React.
In my reducer, I have a create_item case.
I can reach action.category, that can be the word 'currency' or 'country'.
What I want to do is to launch either the method createCurrency or createCountry according what is inside action.category.
That's why I tried to join 'create' and 'action.category' to create a dynamic function name.
But it seems to be a poor idea...
The simplest approach is to create an object which contains an entry where:
the key is a string
the value is a function.
Example:
const myObject = {
myFunction: () => { [... DO SOMETHING...] }
}
Subsequently you will be able to invoke the function, using:
myObject.myFunction();
The above becomes more powerful when you use brackets notation.
Example:
const myString = 'myFunction';
myObject[myString]();

How to parse javascript object string in javascript? [duplicate]

This question already has answers here:
Parsing "relaxed" JSON without eval
(6 answers)
Closed 6 years ago.
I have a string representation of an object, in a template string, like this
const obj = `
{
namespace: 'ignored',
state: {}
}
`
Now I want to parse that into an object, but JSON.parse throws an error.
JSON.parse(obj)
//=> Uncaught SyntaxError: Unexpected token n in JSON at position 13(…)
thats because JSON.parse expect a json string like this
const obj = `
{
"namespace": "ignored",
"state": {}
}
`
Now, I can't manually change my obj object, because is an user input, and can be way more complex. So, is there any way to parse it? before using JSON.parse, maybe some regex, or maybe some other method better than JSON.parse?
Any help is appreciated.
You could do a few things.
Use a proper parser.
Use eval().
For most applications, particularly if there is any user-input there that will end up on other user's computers, eval()'s a terrible idea. Probably only useful here for a throwaway script or similar.
For parsing, define its input grammar, parse it into a tree structure and then directly create the JavaScript object you need. Since it looks like actual JavaScript code, you could use an existing parser and it will be much easier.

Javascript How do I force a string + variable to be evaluated as a variable [duplicate]

This question already has answers here:
is there a way to execute a function when I have its name in a string [duplicate]
(2 answers)
Closed 9 years ago.
Im not even sure how to word this and is probably why I am having trouble finding an answer in google.
When the code is run currentCardRow will equal 1 therefore it should be cardSelected1 which is what is shown in the console.log. I need it to go a step further because cardSelected1 is a variable and I need it to evaluate show in the console log as Invitation. Invitation is an example of a variable for cardSelected1.
I am not sure on what the correct syntax is to make this happen.
var currentCardSelected = "cardSelected" + currentCardRow;
Thanks for your help!
JavaScript has an Eval() function which allows you to evaluate strings as javascript code.
For example
var bar = "123";
var foo = "bar";
console.log(eval(foo));
will print "123" to the console.
For more information on eval, you can consult the MDN docs.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval
Generally, the use of eval() is considered poor practice as it makes the code difficult to read. There are likely more elegant solutions to implement what you have described, however, eval will solve your current problem.
var currentCardSelected = eval("cardSelected" + currentCardRow);
This is how my problem is fixed.

JavaScript /regex/.test() give a function as parameter [duplicate]

This question already has an answer here:
Strange JavaScript idiom - what does "/xyz/.test(function(){xyz;})" do?
(1 answer)
Closed 9 years ago.
I check the Mollzia and MS document, I only find regex.test(str) API. However, I saw a usage of test(function(){}) in John Resig's Class.js which made me very confused.
source code: class.js
the code:
fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
and
fnTest.test(prop[name])
what they do?
on firebug
console.log(/xyz/.test(function(){xyz;}))//true;
console.log(/xyz/.test(function(){}))//false;
console.log(/xyz/.test(function(){console(xyz);}))//true; console(xyz) not run
I think that
fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
is a form of browser feature detection. He's passing a function object to the "test" method, which should convert the function object to a string. If the result of that actually does include the string "xyz", then the "fnTest" variable is initialized to the regex /\b_super\b/. If not, which would be the case when a JavaScript environment wouldn't stringify a function like that for some reason (hint: IE), then "fnTest" is initialized to a regex that'll match anything.

How to validate a JSON String JQuery [duplicate]

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.

Categories