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?
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?
Share Improve this question asked Jul 9, 2013 at 19:11 mateusmasomateusmaso 8,5036 gold badges42 silver badges54 bronze badges 4- 2 There's no native solution because it's an ambiguous problem. You'd need to determine exactly what sorts of things you'd be willing to parse. Something that would just "figure out" the string would be quite challenging (in general). – Pointy Commented Jul 9, 2013 at 19:13
-
1
Parse it as JSON using
JSON.parse
? – gen_Eric Commented Jul 9, 2013 at 19:14 -
1
Do you mean
parseToPrimitive("\"a string\"")
in your first example? It seems more logical to me. – bfontaine Commented Jul 9, 2013 at 19:17 - In JavaScript objects are not primitive values. – Šime Vidas Commented Jul 9, 2013 at 19:21
1 Answer
Reset to default 10This should work
function parseToPrimitive(value) {
try {
return JSON.parse(value);
}
catch(e){
return value.toString();
}
}