Javascript 在Typescript中将字符串消息拆分为数组
我正在尝试将字符串消息拆分为Typescript中的数组。我不能使用逗号,因为有一个json字符串。我试图解析,但出现了一个错误Javascript 在Typescript中将字符串消息拆分为数组,javascript,arrays,json,typescript,Javascript,Arrays,Json,Typescript,我正在尝试将字符串消息拆分为Typescript中的数组。我不能使用逗号,因为有一个json字符串。我试图解析,但出现了一个错误 const msgs = 'string_no_quotes,"string-with@}-weirdchars",{"ckey":null,"email":"user@gmail.com","pass":"password","name&
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())
错误:
SyntaxError: Unexpected token c in JSON at position 1
at JSON.parse (<anonymous>)
经过长时间的试用,通过自定义func解决了这个问题,这不是一个简单的方法,但可以根据需要工作。最初的问题是,输入是作为缓冲区从zmq代理接收的,而来自msg.toString()的数据格式很奇怪 步骤:
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+"]")
}
}
最后的产出:
["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"]
在这里嘿,科斯莫。您希望最终的数据结构是什么样的?您使用的字符串不是有效的JSON(它甚至不是有效的JS/TS字符串),因此我想最好的解决方案是将有效的JSON传递给它。否则,您需要编写一个自定义解析器来遍历字符串,并在它遇到逗号时确定下一步的内容并相应地读取。您的第一行代码无效。您有一个字符串
'string\u no\u quotes',string with quotes',
和一个对象{“ckey”..
一个字符串对象数组[“string\u no\u quotes”,“string with qutoes”,“{/*JSON string*/}”,“opt data”]。我知道JSON.parse试图将字符串解析为对象,但我希望最好解析数组中的对象。感谢jburtonevis,您可以更改数据源以发送格式正确的JSON吗?这几乎肯定比处理此问题更容易。
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))
["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"]