簡體   English   中英

將字符串消息拆分為 Typescript 中的數組

[英]split a string message into array in Typescript

我正在嘗試在 Typescript 中將字符串消息拆分為數組。 我不能使用逗號,因為有一個 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'

const messages:string[] = JSON.parse(msgs.toString())

錯誤 :

SyntaxError: Unexpected token c in JSON at position 1
    at JSON.parse (<anonymous>)

將值放入字符串數組的最佳解決方案是什么。

PS:如果你想知道我為什么想出這么討厭的字符串,它的“ZeroMQ”消息。 而且,我試過,

JSON.parse("["+msgs.toString()+"]")
eval("("+msgs.toString()+")")

經過長時間的試用,使用自定義 func 找到了它,不是直接的,但可以根據需要工作。 最初的問題是輸入是作為來自 zmq 代理的緩沖區接收的,並且有來自 msg.toString() 的奇怪數據格式

腳步:

  1. 使用正則表達式來隔離對象數據,

  2. 用模板字符串替換正則表達式匹配,

  3. 拆分它,替換 '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+"]") } }

電話,

  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"]

這是打字稿播放

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM