简体   繁体   中英

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:

eg 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.

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

您可以尝试javascript-stringify npm软件包。

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

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