prisoner_of_azkaban
prisoner_of_azkaban

Reputation: 758

Convert Object to string in javascript without the quotes in key

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

Answers (3)

user1984
user1984

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

Amardeep Bhowmick
Amardeep Bhowmick

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

redrick.tmn
redrick.tmn

Reputation: 106

You can try javascript-stringify npm package.

Upvotes: 2

Related Questions