[英]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 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, 现在我们可以使用
JSON.stringify(a)
将其转换为字符串,但是输出,
console.log(a)
-> {"b": "c"}
but I want something like this: {b: "c"}
in the original Object format. console.log(a)
-> {"b": "c"}
但是我想要这样的东西: {b: "c"}
采用原始对象格式。
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: 您可以尝试使用Reg-ex,在
String.prototype.replace
调用中使用$1
仅用空格字符替换第一次出现的""
。
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}}`; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.