Reputation: 758
How can I convert an Object to a string so that output is something like this:
e.g. let a = {b: "c"}
Let's assume the above example is our sample Object. Now we can use JSON.stringify(a)
to convert it to string but that outputs,
console.log(a)
-> {"b": "c"}
but I want something like this: {b: "c"}
in the original Object format.
Upvotes: 1
Views: 1668
Reputation: 6828
This code is taken from this answer.
There is a regex solution that is simpler but it has a shortcoming that is inherent to regex. For some edge cases in complex and nested objects it does not work.
const data = {a: "b", "b": "c",
c: {a: "b", "c": "d"}}
console.log(stringify(data))
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}}`;
}
Upvotes: 2
Reputation: 16908
You can try using a Reg-ex, where you replace only the first occurrence of ""
with white space character using $1
in the String.prototype.replace
call:
const a = JSON.stringify({a: "a", b: "b", c: "c"}).replace(/"(\w+)"\s*:/g, '$1:');
console.log(a);
Upvotes: 5