简体   繁体   中英

Parse Javascript Object to JSON-like string, but with single quotes

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.

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM