Guide to converting a log string into JSON using Javascript

I encountered a console log that appears as follows:

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

Is there a way to extract and format this information into JSON like so:

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

Answer №1

Instead of using Regex, I opted for string manipulation to handle the task at hand. Below is the code snippet:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing the template UI to not display the Vue data?

As someone new to Vue, I have defined my Vue code in the following way: import Vue from "vue"; export default Vue.extend({ data: () => { message: "show message"; }, }); <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js ...

Use the JavaScript executor to combine a dynamic string

I have a String variable that retrieves IDs from an Excel sheet. String id = formatter.formatCellValue(sheet.getRow(i).getCell(2)); I am trying to dynamically update the ID using JavaScript executor, but it seems that the concatenation is not working cor ...

Fetching Json data from PHP server

Here is the Json data provided:- {"data":[{"text1":"value1","text2":"value2","text3":"values3"},{"text1":"value1","text2":"value2","text3":"values"},{"text1":"value1","text2":"value2","text3":"values"},{"text1":"value1","text2":"value2","text3":"values"}, ...

Struggling to decipher JSON using jQuery proved to be quite challenging

JSON object (parameters) "selectedShopeNumber":1765653589, "shopeNumbersForSelectedNames":[], "shopeNumbers":[1765653589, 660791222],"shopeNames":["Shope 1","Shope 2"] code var params = JSON.parse("[" + parameters + "]"); for (var i = 0; i < params.s ...

Encountered a 400 error when attempting to send a request to a RestController in Spring MVC

I keep getting a "bad request 400" error when sending a request with parameters to the controller. I have double-checked the syntax but can't find any mistakes. Can someone please review my code and see what's wrong? var url = contextPath+"/bill ...

Seeking guidance: I am currently utilizing Python to implement a regular expression in order to extract and categorize sample restaurant sales data from a .pdf file, and then converting it into a JSON

The regular expression being utilized is ^\s*(\d+)\s*(([A-Za-z]+\s*)+)?(\d+)\s+(.+?)\s+(\d+.\d+)\s+(\d+.\d+)\s+(\d+.\d+)\s+(\d+.\d+)\s+(\d+.\d+)\s ...

Having trouble converting an Amazon S3 function into promises with when/node

I'm having trouble with an AWS S3 asynchronous function and encountering a strange issue. Here is the code snippet: var s3 = new AWS.S3(); var when = require('when'); var nodefn = require('when/node'); var getObjectP = nodefn.lif ...

Strategies for avoiding the issue of multiple clicks on a like button while also displaying an accurate likes

My latest project involves creating a Like button component that features a button and a likes counter text field. The challenge I am facing is that each time I click on the button, it toggles between like and dislike states. However, if I rapidly press ...

What could be causing my UI Bootstrap datepicker-popup to suddenly stop functioning?

After updating to UI Bootstrap 0.11.0, I encountered an issue where my datepickers were no longer appearing correctly. To demonstrate this problem, I have created a plunker which can be viewed here. Essentially, the code snippet causing the problem is as f ...

Analyzing XBRL documents using JavaScript

Looking to extract information from XBRL files like the one found here, I came across a promising npm module called parse-xbrl that claims to be capable of parsing XBRL files. Here is the code snippet I used for implementation: var ParseXbrl = require(&ap ...

CSS Challenge: How to crop an image without using its parent container directly

I'm currently facing a complex CSS challenge that I can't seem to solve. I want to create an image controller (two-by-two layout on two lines) that can display: The top-left image in full size, The top-right with horizontal scrolling, The botto ...

jQuery Triggered Download Resulting in 'Error: Connection Issue'

I need to trigger a download using a JQuery AJAX request once it's finished. EXAMPLE CODE: $('.getPDF').click(function(){ var filepath = 'localhost:3000/pdf/formula-' + this.id + '.pdf'; $.ajax({ url: '/formu ...

JSDOM failing to retrieve complete list of elements from webpage

I'm currently struggling with a simple webscraper using JSDOM. Here's the code snippet I've been working on: const axios = require("axios"); const jsdom = require("jsdom"); const { JSDOM } = jsdom; let v = "15" ...

Refine the Vuex state with a filter

Currently, I've progressed in my Vue development journey and started exploring the implementation of Vuex for state management. In the past, I had a main Vue component that handled search functionality, an array of items to iterate over, and the iter ...

What is the process for creating a server-side API call?

I've designed a front-end application that uses an API to retrieve data. The problem I'm facing is that in order to access the API, I need to use an API Key. If I include the API key in the client-side code, it will be visible to users. How can I ...

What is the reasoning behind the return type of void for Window.open()?

There is a difference in functionality between javascript and GWT in this scenario: var newWindow = window.open(...) In GWT (specifically version 1.5, not sure about later versions), the equivalent code does not work: Window window = Window.open("", "", ...

Updating the video tag's source attribute using JSON information

I am in the process of creating a unique video player using HTML and Javascript that will sequentially play a set of videos until all 6 have been displayed. The URLs for these videos are stored within an array that is mapped in a .json file named clips.jso ...

"Utilizing AJAX to set an array as a global variable

Struggling with storing data values from an AJAX response XML into a global array, and then attempting to call a function that removes specific elements from it. The issue lies in the fact that the array is not declared as global. Here's the current c ...

Vue.js - Error: Module not found: Cannot locate module 'lottie-vuejs'

I've been attempting to integrate lottie-vuejs into my project. After running the npm install command and following the steps outlined here, I encountered an issue. Unfortunately, I received the following error message: Module not found: Error: Can ...

The challenge of transferring documents to the server

There is a form on the webpage where users can select a file and click a button to send it. <form enctype="multipart/form-data"> <input type="file" id="fileInput" /> <button type="button&quo ...