1

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.

prisoner_of_azkaban
  • 700
  • 1
  • 8
  • 26

3 Answers3

5

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);
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44
2

You can try javascript-stringify npm package.

2

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}}`;
}
user1984
  • 5,990
  • 2
  • 13
  • 32