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

前端 未结 3 946
独厮守ぢ
独厮守ぢ 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:48

    As eval() has security flaws, it's better not to use it. A possible way would be creating a own parser to convert it to JSON string and then apply JSON.parse(). Something like below

    function toJSONString(input) {
       const keyMatcher = '([^",{}\\s]+?)';
       const valMatcher = '(.,*)';
       const matcher = new RegExp(`${keyMatcher}\\s*:\\s*${valMatcher}`, 'g');
       const parser = (match, key, value) => `"${key}":${value}`
       return input.replace(matcher, parser);
    }
    
    JSON.parse(toJSONString('{a: 0, b: "haha"}'))
    

提交回复
热议问题