I know there is parseInt, parseFloat, and other workarounds to parse Booleans and Arrays from a String in javascript.
What I would need is a method with similar behavior when you use a Object string to JSON parser and the result is a Object with type converted values.
Here is what I want:
parseToPrimitive("a string") => "a string"
parseToPrimitive("1") => 1
parseToPrimitive("true") => true
parseToPrimitive("[1, 2, 3]") => [1, 2, 3]
Any native solution for this or any library?
This should work
function parseToPrimitive(value) {
try {
return JSON.parse(value);
}
catch(e){
return value.toString();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With