0

This is my Javascript object that I converted into a string (JSON)

var myObj = {
    name: 'John',
    age: 25,
    group: 'O+'
}

console.log(JSON.stringify(myObj));

I need the output with single quotes (apostrophes) (') and not double quotes ("). Also no quotes or apostrophes on the indexes/keys. I want it to look like this:

{name:'John',age:25,group:'O+'}

I tried this:

var myObj = {
    name: 'John',
    age: 25,
    group: 'O+'
}

console.log(JSON.stringify(myObj).replace(/"([^"]+)":/g, '$1:'));

This removes the quotes on the indexes/keys but the values still have quotes in them. Need to replace them with apostrophes. Tried some more regexes but they did not work.

1
  • 1
    You should ask yourself why you need to print it in this specific way. It's an object and it is not made for printing it. Commented Mar 14, 2020 at 14:16

2 Answers 2

2

If you add some more replaces at the end of that stringify, you can actually get what you want. Here is your example:

var myObj = {
    name: 'John',
    age: 25,
    group: 'O+'
}

console.log(JSON.stringify(myObj).replace(/"([^"]+)":/g, '$1:').replace(/\\"/g, '"')
    .replace(/([\{|:|,])(?:[\s]*)(")/g, "$1'")
    .replace(/(?:[\s]*)(?:")([\}|,|:])/g, "'$1")
    .replace(/([^\{|:|,])(?:')([^\}|,|:])/g, "$1\\'$2"));

You can find this exact example on a different forum on stackexchange. Here is the link.

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

Comments

0

You can use JSON.parse reviver to format the values like this.

var myObj = {
    name: 'John',
    age: 25,
    group: 'O+',
    bool:true,
    hello:{
        a:'bb'
    }
}
const reviver =(key, value)=>{
if(typeof value === 'string'){
  return `'${value}'`
}
return value
}
var a = JSON.parse(JSON.stringify(myObj), reviver);
console.log(JSON.stringify(a).replace(/"/g,''));

1 Comment

This changes the field type of age.

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.