简体   繁体   English

使用正则表达式引用JavaScript对象键?

[英]Quoting javascript object keys using a regex?

I have some key value pairs like this inside a string: 我在字符串中有一些像这样的键值对:

const process = 
`
abeezee: "ABeeZee",
abel: "Abel",
abhaya-libre: "Abhaya Libre",
`

I need to quote the keys such that the entire thing becomes valid json when wrapped with {} . 我需要引用这些键,以便当用{}包裹时,整个东西变成有效的json。 However not sure how to do this using a regex? 但是不确定如何使用正则表达式执行此操作?

The end result needs to look like this: 最终结果应如下所示:

"abeezee": "ABeeZee",
"abel": "Abel",
"abhaya-libre": "Abhaya Libre",

You don't need regex here, you can achieve that result using Array.split . 您在这里不需要正则表达式,可以使用Array.split实现该结果。

 const process = `abeezee: "ABeeZee", abel: "Abel", abhaya-libre: "Abhaya Libre"`; const result = process.split(',\\n') .map(line => { const [key, value] = line.split(':'); return `'${key}':${value}`; }) .join(',\\n'); console.log(result); 

You may use this code snippet: 您可以使用以下代码段:

 const process = ` abeezee: "ABeeZee", abel: "Abel", abhaya-libre: "Abhaya Libre", ` var jsonstr = '{' + process.replace(/^[^\\s:]+/gm, '"$&"').replace(/,\\s*$/, '\\n') + '}'; console.log( jsonstr ) /* == Output == { "abeezee": "ABeeZee", "abel": "Abel", "abhaya-libre": "Abhaya Libre" } */ 

You also need to trim the trailing comma and surround it with {} to have valid JSON: 您还需要修剪尾随逗号并用{}以具有有效的JSON:

 const process = ` abeezee: "ABeeZee", abel: "Abel", abhaya-libre: "Abhaya Libre", `; const json = '{\\n' + process .replace(/^\\s*|[\\s,]*$/g,'') // trim trailing comma and leading/trailing whitespace .replace(/^/gm, ' "') // Add quotes at beginning of lines .replace(/^([^:]*):/gm, '$1":') // Add quotes before the first colon on each line + '\\n}'; console.log( json ); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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