Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

160
Visualizações
String array to object array with key-value pair inside the string

I want to construct an object array with key-value pair from a string array.

the string array format:

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

the object array format:

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

stringArray = [
   "2021-08-09T02:12:51.259Z - error - {\"user_id\":\"1234-1111\",\"details\":\"Cannot find user orders list\",\"code\": 404,\"err\":\"Not found\"}",
   "2022-08-09T02:12:51.275Z - error - {\"user_id\":\"1111-1234\",\"details\":\"Cannot find user orders list\",\"code\":404,\"err\":\"Cannot find user orders list"}"
];

objectArray = [
   {
      "timestamp":1628475171259,
      "loglevel":"error",
      "userId":"1234-1111",
      "err":"Not found"
   },
   {
      "timestamp":1660011171275,
      "loglevel":"error",
      "userId":"1111-1234",
      "err":"Cannot find user orders list"
   }
];
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You may deconstruct each line as "timestamp" - "logLevel" - "jsonStringified"

The later can be JSON.parsed to retrieve the object

Note that maybe you should ensure that every line holds the format. Otherwise you would have errors to handle (what if no jsonStringified, what is someone else outputted some random lines, etc)

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 })

about 4 years ago · Juan Pablo Isaza Relatório

0

In Java, you can do this by splitting using tokens

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);

Kindly add null check wherever needed

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda