How to convert a JSON-like (not JSON) string to an object?

前端 未结 3 948
独厮守ぢ
独厮守ぢ 2021-01-24 12:50

We all know we can use JSON.parse() to convert the string \'{\"a\":0,\"b\":\"haha\"}\' to the object {a: 0, b: \'haha\'}.

But can

3条回答
  •  北荒
    北荒 (楼主)
    2021-01-24 13:44

    Something like this might work:

    function evalJsString(str) {
        let a = null;
        try {
            eval('a = ' + str);
        } catch (err) {
            console.error(err);
        }
        if(typeof a === "object")
          return a;
        else
          return null;
    }
    
    evalJsString('({a: 0, b: "haha"})');
    

提交回复
热议问题