Create a JSON object in JavaScript that will specifically retrieve and return only the values where the value exists

These are the specific objects I am working with:

{"event":"auth success"}
{"event":"status","args":["running"]}
{"event":"console output","args":["openjdk version \"11.0.10\" 2021-01-19"]}
{"event":"console output","args":["OpenJDK Runtime Environment 18.9 (build 11.0.10+9)"]}
{"event":"console output","args":["OpenJDK 64-Bit Server VM 18.9 (build 11.0.10+9, mixed mode, sharing)"]}

I am incorporating this in my JavaScript code:

    var JSONObject = JSON.parse(event.data);
    var theDiv = document.getElementById("cli");
    theDiv.innerHTML += "<div>"+JSONObject["args"]+"</div>";

The result displayed is as follows:

undefined
running
openjdk version "11.0.10" 2021-01-19
OpenJDK Runtime Environment 18.9 (build 11.0.10+9)
OpenJDK 64-Bit Server VM 18.9 (build 11.0.10+9, mixed mode, sharing)

Is there a way to extract only the value of args when event is equal to "console output"?

Answer №1

In the event stream scenario where you receive objects one by one, you can achieve the desired outcome with this approach:

var json = `{"event":"console output","args":["OpenJDK Runtime Environment 18.9 (build 11.0.10+9)"]}`;

var JSONObject = JSON.parse(json);
var theDiv = document.getElementById("cli");
if(JSONObject.event === "console output") {
  theDiv.innerHTML += "<div>" + JSONObject["args"] + "</div>";
}
<div id="cli"></div>

If the objects are in a format different from valid JSON and separated by newline characters, then you will need to split them and parse each object individually like so:

var JSONObjects = json.split("\n").map(line => JSON.parse(line));
console.log(JSONObjects);
JSONObjects.forEach(obj => {
  var theDiv = document.getElementById("cli");
  if (obj.event === "console output") {
    theDiv.innerHTML += "<div>" + JSONObject["args"] + "</div>";
  }
});

Answer №2

function receiveMessage(event) {
            var targetDiv = document.getElementById("cli");
            var data = event.data.replaceAll("\u003e\u001b[2K\r", "");
            var parsedData = JSON.parse(data);
            if(parsedData.event === "console output") {
                targetDiv.innerHTML += "<div>" + data + "</div>";
                
            }
        };

display result

{"event":"console output","args":["\u003e\u001b[2K\r[16:11:16] [Server thread/INFO]: [Server] hello"]}

What could be causing the replacement issue?

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

Testing an AngularJS factory that returns a promise and mocking a service that utilizes $http

My service includes a method that returns an $http promise: function sessionService($http, serviceRoot) { return { getAvailableDates: function () { return $http.get(serviceRoot + '/session/available_dates'); } ...

Can someone assist me with navigating through my SQL database?

Struggling with a script that searches multiple fields in the same table, I need it to return results even if one or three parameters are left blank. My attempts using PHP and MySql have been fruitless so far, which is why I am reaching out to the experts ...

Effective strategies for utilizing AngularJS broadcast across various states within your application

Having issues with my editPrcChallenge function. I am broadcasting the challengekey in order to route the user to a child state, but for some reason it's not entering the function. Any thoughts on what might be wrong with my implementation? This is w ...

What is the most effective way to compress a paragraph and fill in the remainder with '...'?

Here is some content wrapped in a paragraph, see below: <div style="width:30px"> <p>12345678901234567890abcdefghijklmnopqrstuvwxyzIlovePaulinaVega</p> </div> We are aware that this content will be displayed on multiple lines due ...

The most lightweight way to serialize a basic data structure

I have a basic data structure that needs to be serialized efficiently without adding unnecessary bulk. Which method do you think is the most space-efficient? Creating custom serialization/deserialization using unique separators like "#" or any other char ...

Issue with jQuery selection in ChromeI'm experiencing a problem with

After entering a value into an input, I have code that should run when the focus exits the input field. $("#guest-level option[id='"+ result.BookingInfo.guestLevelCode +"']").attr("selected", "selected"); This code runs smoothly in Firefox but ...

Unable to transform JSON array into a string

I am encountering an issue where the server is not responding with the expected data. Instead, I am receiving a token error '<', despite trying various solutions. $(document).ready(function() { $.ajax({ url:"url", dataTyp ...

Guide on mocking a function inside another function imported from a module with TypeScript and Jest

I have a function inside the action directory that I want to test: import { Action, ActionProgress, ActionStatus, MagicLinkProgress } from '../../interfaces' import { areSameActions } from '../actionsProgress' export const findActionPr ...

Guide to selecting a button within a Chrome Extension

Currently, I am in the process of setting up a basic Chrome extension that will automatically click on an element once the extension button is clicked. I have done some research on this topic, but unfortunately, I haven't been able to find a straight ...

How to activate a function or event upon closing a browser tab with JavaScript

How can a function be triggered when a user closes the browser tab, preventing it from closing immediately and instead displaying a popup prompting the user to either proceed to another page or close the tab? Scenario: In the event that a user attempts t ...

Quickly remove items from a list without any keywords from the given keywords list

This spreadsheet contains two sheets named "RemoveRecords" and "KeywordsList". I need to use app scripts to remove any records that are not included in the "KeywordsList" sheet. This should be done by searching through the "ArticleLink" column. Although ...

Having trouble selecting a TinyMCE iframe using a JavaScript file

The issue with selecting the TinyMCE iframe using a JS file. $(document).ready(function() { console.log("Connected!!"); let iframe = document.getElementById("myTextarea_ifr"); let body = iframe.contentWindow.document.querySelector("#tinymce"); ...

Troubleshooting HTML Output Display Issues

I've been trying to post my content exactly as I submit it, but for some reason, it's not working. When I enter two paragraphs in a post, the output doesn't maintain that formatting. Instead, it removes the paragraph breaks and displays the ...

Utilize the individual JSON objects within C++ Crow

I've been working with a cpp crow library and I'm facing challenges accessing individual objects. Below is the code snippet I'm using: CROW_ROUTE(app,"/hello/<string>") ([](string name){ crow::json::wvalue x; x["name"] = "llllds" ...

At what point should the term "function" be included in a ReactJS component?

As a beginner in ReactJS, I have been working through some tutorials and noticed that some code examples use the keyword function while others do not. This got me wondering what the difference is and when I should use each one. Render Example with functi ...

Unable to redirect from login page to dashboard using AJAX with Flask backend

Using the post method for login, my ajax function successfully sends data to my flask backend server [confirmed by the response received]. However, after receiving the response from the backend, the ajax success handler fails to navigate/redirect to the da ...

Implementing updates to a website from a database without the need for a page refresh

I am eager to delve into the world of AJAX and have identified a seemingly straightforward challenge that I believe will serve as an informative learning experience. Imagine a scenario where users are continuously adding new entries to a database table. ...

Unable to get md-virtual-repeat to work within md-select?

Attempting to use md-select to showcase a large amount of data is causing the browser to freeze upon opening. To address this, I tried implementing md-virtual repeat within md-select for improved performance. However, the code doesn't seem to be funct ...

Adapting the column width to display or hide content with CSS styling

I have a row with 2 columns. The left column contains my main content and the right column is a chatroom. I would like users to be able to minimize and open the chatroom, which I already know how to do. However, when the chatroom is open, I want the left ...

What is the best way to transfer data from a fully filled out JSON form to a PHP database

Is there a way to automatically send a completed JSON form when the device detects an internet connection? I am facing the challenge of dynamically generated IDs for each question and need to figure out how to submit the data to the database on button cl ...