How to parse a log string in Javascript to a JSON



I have a console string that looks like this:

2021-01-06T09:06:05.541212726Z D saveGarment: Function execution took 736 ms, finished with status code: 204
2021-01-06T09:06:10.844901031Z D saveGarment: Function execution started
2021-01-06T09:06:16.153Z ? saveGarment: CORE
2021-01-06T09:06:18.134508823Z D saveGarment: Function execution took 7470 ms, finished with status code: 200
2021-01-06T09:06:19.546Z ? saveGarment: { message: 'fail' }

How can I parse this string to a JSON so that it looks like this:

{
  {
    date: '2021-01-06'
    time: '09:06:05'
    type: 'D'
    function: 'saveGarment'
    message: 'Function execution took 736 ms'
    statusCode: 204
  },
}

Answer

It seems a little bit hard to use Regex, I just use the string manipulation to deal with that, here is the code:

let consoleLog = `2021-01-06T09:06:05.541212726Z D saveGarment: Function execution took 736 ms, finished with status code: 204
2021-01-06T09:06:10.844901031Z D saveGarment: Function execution started
2021-01-06T09:06:16.153Z ? saveGarment: CORE
2021-01-06T09:06:18.134508823Z D saveGarment: Function execution took 7470 ms, finished with status code: 200
2021-01-06T09:06:19.546Z ? saveGarment: { message: 'fail' }`;

let logs = consoleLog.split('n');
let results: any = [];
console.clear();
logs.forEach(log => {
    let twoParts = splitFirstCh(log, ' ');
    let dateTime = twoParts[0];
    let twoParts1 = splitFirstCh(twoParts[1], ' ');
    let typeStr = twoParts1[0];
    let twoParts2 = splitFirstCh(twoParts1[1], ':');
    let message = '', statusCode = '';
    if (twoParts2[1].indexOf('status code') > -1) {
        message = splitLastCh(twoParts2[1], ',')[0];
        statusCode = splitLastCh(twoParts2[1], ':')[1].trim();
    } else if (twoParts2[1].indexOf('{') > -1) {
        message = splitLastCh(twoParts2[1], ':')[1].replace('}', '').trim();
        statusCode = '';
    } else {
        message = twoParts2[1].trim();
        statusCode = '';
    }

    let functionStr = twoParts2[0];
    results.push({
        date: new Date(dateTime).toLocaleDateString(),
        time: new Date(dateTime).toLocaleTimeString(),
        'type': typeStr,
        'function': functionStr,
        message: message,
        statusCode: statusCode
    });
});

console.log(results);

function splitFirstCh(data: string, ch: string) {
    return [data.substr(0, data.indexOf(ch)), data.substr(data.indexOf(ch) + 1)];
}

function splitLastCh(data: string, ch: string) {
    return [data.substr(0, data.lastIndexOf(ch)), data.substr(data.lastIndexOf(ch) + 1)];
}


Source: stackoverflow