There are numerous instances of poorly formatted string objects retrieved from APIs, outdated code, and more. A bad format does not necessarily cause errors in the code itself, but rather triggers errors when attempting to parse with JSON.parse().
// Incorrectly wrapped key syntax
var str = "{ a: 2 }";
console.log( JSON.parse( str ) );
// SyntaxError: JSON.parse: expected property name or '}' at line 1 column 3 of the JSON data
// Incorrect 'key' or 'value' syntax
var str = " { 'a': 2 } ";
console.log( JSON.parse( str ) );
// SyntaxError: JSON.parse: expected property name or '}' at line 1 column 3 of the JSON data
// Syntax that is correct
var str = '{ "a": 2 }';
console.log( JSON.parse( str ) );
// Object { a: 2 }
A solution exists:
// Convert any-formatted object string to well-formatted object string:
var str = "{'a':'1',b:20}";
console.log( eval( "JSON.stringify( " + str + ", 0, 1 )" ) );
/*
"{
"a": "1",
"b": 20
}"
*/
// Convert any-formatted object string to an object:
console.log( JSON.parse( eval( "JSON.stringify( " + str + ", 0, 1 )" ) ) );
// Object { a: "1", b: 20 }