[英]String to JavaScript JSON/Object
I have string like array and object want to convert it to pure javascript object or JSON.我有像数组这样的字符串,object 想将其转换为纯 javascript object 或 JSON。
My string example:我的字符串示例:
"`{keyOne: valueOne, KeyTow: [10, true, null, 10%], keyThree: {hello: hi}}`"
I found a solution converting string to JSON here https://stackoverflow.com/a/42907123/4578250我在这里找到了一个将字符串转换为 JSON 的解决方案https://stackoverflow.com/a/42907123/4578250
the result with above solution is:上述解决方案的结果是:
{"keyOne": "valueOne", "KeyTow": [10, true, null, "10"%], "keyThree": {"hello": "hi"}}
I want the result like:我想要这样的结果:
{"keyOne": "valueOne", "KeyTow": [10, true, null, "10%"], "keyThree": {"hello": "hi"}}
But I'm not able to convert the string with percentage symbol.但我无法转换带有百分比符号的字符串。 any help will be appreciated.任何帮助将不胜感激。
Just quote all alphanumeric sequences, except for those that are true, false, null, or a number:只需引用所有字母数字序列,真、假、null 或数字除外:
let s = "`{keyOne: valueOne, KeyTow: [10, true, null, 10%], keyThree: {hello: hi}}`" let r = s.replaceAll('`', '').replaceAll(/([\w%]+)/g, m => m.match(/^\d[\d.]*$/) || ['true','false','null'].includes(m)? m: `"${m}"`) console.log(JSON.parse(r))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.