I would like to allow a user to enter some input, and the program to parse that as a js type, if it can. For example, in what the user types into the text input is:
Would the following accomplish this in a very basic fashion, ignoring nested objects and such?
function parseValueFromText(text) {
try {
return JSON.parse(text);
} catch(e) {
if (e instanceof SyntaxError) {
return text;
} else {
throw e;
}
}
}
let a=parseValueFromText('hello'),
b=parseValueFromText(123);
console.log(a, typeof a);
console.log(b, typeof b);
Your implementation is pretty close, but if JSON.parse results in a string then you likely want the original string, not the result of the parse.
Also, I think that any exception should result in the original string.
function parseValueFromText(text) {
try {
const result = JSON.parse(text);
if (typeof result !== 'string') return result;
} catch {}
return text;
}