简体   繁体   English

将对象转换为javascript中的字符串,而键中没有引号

[英]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.

相关问题 将JavaScript对象转换为JSON字符串以获取键和值 - Convert JavaScript Object to JSON String for Key and Values JavaScript对象字符串/引用问题 - Javascript object string/quotes issue 关于Javascript速记对象引用的问题 - Question about Javascript Shorthand object quotes in the key javascript将双引号转换为字符串中的单引号 - javascript convert double quotes into single quote in a string 将不带双引号的javascript对象包含键/值转换为纯JSON - Convert javascript object containg keys/values without double quotes to pure JSON 将Python字典转换为没有字符串键的JSON对象 - Convert Python dictionary to JSON object without string key JavaScript请求对象-将键作为变量转换为字符串 - JavaScript request object- convert key as a variable to string Javascript将具有数组字符串键的对象转换为键/名称值的 - Javascript convert object with array string keys to key/name value's 用于将JSON键值对象转换为查询字符串的JavaScript函数 - JavaScript function to convert JSON key-value object to query string 如何在不使用eval的情况下将javascript中的嵌套数组字符串转换为不带引号的数组,字符串也可以是Z25F7E525B5C0641E1EB1FB3BDEBEB15B5Z的形式 - How to convert a string of nested array to array without quotes in javascript without the use of eval, string can be also in a form of latex
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM