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.

5
  • 1
    when in doubt for loop out Commented Aug 18, 2019 at 17:25
  • Why do you want the original not valid JSON format? Commented Aug 18, 2019 at 17:27
  • @mplungjan I need to pass this object as part of graphql query. Issue is I can only pass it like this: (a: "b", c: "d"). It throws error if string is like this: ("a": "b", "c":"d") Commented Aug 18, 2019 at 17:29
  • 2
    That is unfortunate. Perhaps fix or ask to have the graphql code fixed Commented Aug 18, 2019 at 17:35
  • 1
    stackoverflow.com/questions/11233498/… Commented Aug 18, 2019 at 17:44

3 Answers 3

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);

Sign up to request clarification or add additional context in comments.

Comments

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}}`;
}

Comments

2

You can try javascript-stringify npm package.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.