[英]split a string message into array in Typescript
I'm trying to split a string message into array in Typescript.我正在尝试在 Typescript 中将字符串消息拆分为数组。 I cannot use comma as there's a json string.
我不能使用逗号,因为有一个 json 字符串。 I tried to parse but I'm getting an error.
我尝试解析,但出现错误。
const msgs = 'string_no_quotes,"string-with@}-weirdchars",{"ckey":null,"email":"user@gmail.com","pass":"password","name":{"firstName":"User","middleName":"","lastName":"Name"},"address":{"street": "test street", "country":"some country", "zip": "639821"},"status":1},opt-data'
const messages:string[] = JSON.parse(msgs.toString())
The error :错误 :
SyntaxError: Unexpected token c in JSON at position 1
at JSON.parse (<anonymous>)
What could be a best solution to get values in to string array.将值放入字符串数组的最佳解决方案是什么。
PS: If you wonder why I came up with such nasty string, its 'ZeroMQ' message. PS:如果你想知道我为什么想出这么讨厌的字符串,它的“ZeroMQ”消息。 And, i tried,
而且,我试过,
JSON.parse("["+msgs.toString()+"]")
eval("("+msgs.toString()+")")
Got it figured out with a custom func after a long tryout, not a straight forward, but works as needed.经过长时间的试用,使用自定义 func 找到了它,不是直接的,但可以根据需要工作。 The original problem was the input is received as a buffer from zmq broker and there's that weird format of data from msg.toString()
最初的问题是输入是作为来自 zmq 代理的缓冲区接收的,并且有来自 msg.toString() 的奇怪数据格式
Steps:脚步:
Used a regex to segregate the object data,使用正则表达式来隔离对象数据,
replace the regex match with template string,用模板字符串替换正则表达式匹配,
split it, replace the 'made' array and return it.拆分它,替换 'made' 数组并返回它。
export const parseTheCrapOutOfThatDamnString = (paramString: string) => { const regEx = RegExp("(?<={)(.*)(?=})") //(?<={)(.*)(?=}) //https://regexr.com/2tr5t if(regEx.test(paramString)) { var theMatch:string = `${_.head(paramString.match(regEx))}` || "" //;console.log(`\\n${theMatch}\\n`) var paramsArray = _.replace(paramString, theMatch, "replaceable").split(',') //;console.log(paramString) paramsArray[paramsArray.indexOf('{replaceable}')] = JSON.parse(`{${theMatch}}`) return paramsArray; }else { return JSON.parse("["+paramString+"]") } }
the call,电话,
const msgs = 'string_no_quotes,"string-with@}-weirdchars",{"ckey":null,"email":"user@gmail.com","pass":"password","name":{"firstName":"User","middleName":"","lastName":"Name"},"address":{"street": "test street", "country":"some country", "zip": "639821"},"status":1},opt-data'
console.log(parseTheCrapOutOfThatDamnString(msgs))
the final output:最终输出:
["string_no_quotes", "string-with@}-weirdchars", {
"ckey": null,
"email": "user@gmail.com",
"pass": "password",
"name": {
"firstName": "User",
"middleName": "",
"lastName": "Name"
},
"address": {
"street": "test street",
"country": "some country",
"zip": "639821"
},
"status": 1
}, "opt-data"]
here it is Typescript play这是打字稿播放
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.