簡體   English   中英

字符串數組到 object 數組,字符串內有鍵值對

[英]String array to object array with key-value pair inside the string

我想用字符串數組中的鍵值對構造一個 object 數組。

字符串數組格式:

['<ISO Date> - <Log Level> - {"transactionId: "<UUID>", "details": "<message event/action description>", "err": "<Optionall, error description>"}']

object 數組格式:

[{"timestamp": <Epoch Unix Timestamp>, "loglevel": "<loglevel>", "transactionId: "<UUID>", "err": "<Error message>" }]

stringArray = [
   "2021-08-09T02:12:51.259Z - error - {\"transactionId\":\"9abc55b2-807b-4361-9dbe-aa88b1b2e978\",\"details\":\"Cannot find user orders list\",\"code\": 404,\"err\":\"Not found\"}",
   "2022-08-09T02:12:51.275Z - error - {\"transactionId\":\"9abc55b2-807b-4361-9dbe-aa88b1b2e978\",\"details\":\"Cannot find user orders list\",\"code\":404,\"err\":\"Cannot find user orders list"}"
];

objectArray = [
   {
      "timestamp":1628475171259,
      "loglevel":"error",
      "transactionId":"9abc55b2-807b-4361-9dbe-aa88b1b2e978",
      "err":"Not found"
   },
   {
      "timestamp":1660011171275,
      "loglevel":"error",
      "transactionId":"9abc55b2-807b-4361-9dbe-aa88b1b2e97",
      "err":"Cannot find user orders list"
   }
];

您可以將每一行解構為"timestamp" - "logLevel" - "jsonStringified"

后者可以是JSON.parse d 來檢索 object

請注意,也許您應該確保每一行都包含格式。 否則你會有錯誤需要處理(如果沒有jsonStringified,其他人輸出了一些隨機行,等等)

 stringArray = [ "2021-08-09T02:12:51.259Z - error - {\"transactionId\":\"9abc55b2-807b-4361-9dbe-aa88b1b2e978\",\"details\":\"Cannot find user orders list\",\"code\": 404,\"err\":\"Not found\"}", "2022-08-09T02:12:51.275Z - error - {\"transactionId\":\"9abc55b2-807b-4361-9dbe-aa88b1b2e978\",\"details\":\"Cannot find user orders list\",\"code\":404,\"err\":\"Cannot find user orders list\"}" ]; const tsCapture = '(.{'+"2022-08-09T02:12:51.275Z".length+'})' const levelCapture = '(error|warning|debug)' const stringCapture = '(.+)' const reg = new RegExp('^'+tsCapture + ' - ' + (levelCapture) + ' - ' + stringCapture+'$') const parsed = stringArray.map(line => { const [_, timestamp, logLevel, str] = line.match(reg) return {timestamp, logLevel, ...JSON.parse(str)} }) console.log({ parsed })

在 Java 中,您可以通過使用令牌拆分來做到這一點

JSONArray jsonArray = new JSONArray();
        for(int i=0;i<stringArray.length; i++) {
            String string = stringArray[i];
            String[] stringSplit = string.split(" - ");
            JSONObject object = new JSONObject();
            object.put("timestamp", stringSplit[0]);
            object.put("loglevel", stringSplit[1]);
            String[] transtactionDetailSplit = stringSplit[2].split(":|,");
            object.put("transactionId", transtactionDetailSplit[1]);
            object.put("err", transtactionDetailSplit[7]);
            jsonArray.add(object);
        }
        System.out.println(jsonArray);

請在需要的地方添加 null 檢查

暫無
暫無

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

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