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
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"}'))