最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Parse a string into primitive values in Javascript - Stack Overflow

programmeradmin1浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 10

This should work

function parseToPrimitive(value) {
    try {
        return JSON.parse(value);
    }
    catch(e){
        return value.toString();
    }
}
发布评论

评论列表(0)

  1. 暂无评论