Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse a string into primitive values in Javascript

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?

like image 990
mateusmaso Avatar asked Sep 15 '25 10:09

mateusmaso


1 Answers

This should work

function parseToPrimitive(value) {
    try {
        return JSON.parse(value);
    }
    catch(e){
        return value.toString();
    }
}
like image 154
Joe Avatar answered Sep 18 '25 01:09

Joe