This simple regular expression solution works to unquote JSON property names in most cases:
const object = { name: 'John Smith' };
const json = JSON.stringify(object); // {"name":"John Smith"}
console.log(json);
const unquoted = json.replace(/"([^"]+)":/g, '$1:');
console.log(unquoted); // {name:"John Smith"}
Extreme case:
var json = '{ "name": "J\\":ohn Smith" }'
json.replace(/\\"/g,"\uFFFF"); // U+ FFFF
json = json.replace(/"([^"]+)":/g, '$1:').replace(/\uFFFF/g, '\\\"');
// '{ name: "J\":ohn Smith" }'
Special thanks to Rob W for fixing it.
Limitations
In normal cases the aforementioned regexp will work, but mathematically it is impossible to describe the JSON format with a regular expression such that it will work in every single cases (counting the same number of curly brackets is impossible with regexp.) Therefore, I have create a new function to remove quotes by formally parsing the JSON string via native function and reserialize it:
function stringify(obj_from_json) {
if (typeof obj_from_json !== "object" || Array.isArray(obj_from_json)){
// not an object, stringify using native function
return JSON.stringify(obj_from_json);
}
// Implements recursive object serialization according to JSON spec
// but without quotes around the keys.
let props = Object
.keys(obj_from_json)
.map(key => `${key}:${stringify(obj_from_json[key])}`)
.join(",");
return `{${props}}`;
}