Extracting keys and values from a JSON string for analysis

My current code for the service now rest outbound call is functioning correctly. However, I am facing issues while trying to parse the JSON body in the second REST call and fetch values in the desired table format.

 try { 
 var r = new sn_ws.RESTMessageV2('test', 'post');

 var response = r.execute();
 var responseBody = response.getBody();
 var httpStatus = response.getStatusCode();
 gs.print(response.getBody());
 gs.print(response.getStatusCode());
 var JsonObject = JSON.parse(responseBody);
 var sid = JsonObject.sid; 
 gs.print(sid);

 var r1 = new sn_ws.RESTMessageV2('gateways', 'POST' );
 r1.setRequestHeader("X-chkp-sid",sid );
 var response1 = r1.execute();
 var responseBody1 = response1.getBody();
 var httpStatus = response1.getStatusCode()
 gs.print(response1.getBody());
 var parser = new JSONParser();
 var jsonObj = parser.parse(responseBody1);
 var outputString = 'Name Domain-Name OS Cluster-Members UID';
 for (var i=0; i < jsonObj.objects.length; i++) {
     var obj = jsonObj.objects[i];
     outputString = outputString + "\n" + obj.name + ", " + obj.domain.name + ", " + obj["operating-system"] + ", " + obj["cluster-member-names"] + ", " + obj.uid;
 }

 gs.log(outputString);
}
catch(ex) {
 var message = ex.message;
}​

The expected output should be like this:

Link to image

However, the actual output that I am getting is:

*** Script: Name Domain-Name OS Cluster-Members UID
clus-cn-1, dom-cn-1, Gaia, dev-cn-c1,dev-cn-c2, 16b96771-d13a-4c11-b457-9c0861aaf3c8
clus-cn-2, dom-cn-2, Gaia, dev-cn-c3,dev-cn-c4, 385c0a22-275c-4a70-9489-2b6ccd191eb8
dev-cn-c1, dom-cn-1, undefined, undefined, 4652da03-0e2f-4a0a-880c-338396be0818
dev-cn-c2, dom-cn-1, undefined, undefined, 2dbbbfd4-80ac-4fd9-b792-0a5b468c6409
dev-cn-c3, dom-cn-2, undefined, undefined, 6037e235-f19a-49ac-a39c-4889d979acbe
dev-cn-c4, dom-cn-2, undefined, undefined, 022c44df-9271-46db-b782-da084c476dd2
dom_cn_1_Server, dom-cn-1, Unknown OS, undefined, 4f417c60-3541-4c0f-a542-9a100d857077
dom_cn_2_Server, dom-cn-2, Unknown OS, undefined, cebecd33-1efb-4530-9de9-7c666e588ee7

I need to prevent the displayed values after the first two lines.

This is a sample of the provided JSON data:

{
"objects" : [ {
    "uid" : "16b96771-d13a-4c11-b457-9c0861aaf3c8",
    "name" : "clus-cn-1",
    "type" : "CpmiGatewayCluster",
    "domain" : {
      "uid" : "16280a32-183a-4050-b698-f59dbe488da6",
      "name" : "dom-cn-1",
      "domain-type" : "domain"
    },
    ...
}

Answer №1

It appears that the code is functioning as intended.

If you're looking to specifically filter out only the lines with an OS name of Gaia, you can easily achieve this by modifying your for loop like so:

for (var i=0; i < jsonObj.objects.length; i++) {
    if (obj["operating-system"] == "Gaia") {
        var obj = jsonObj.objects[i];
        outputString = outputString + "\n" +
            obj.name + ", " +
            obj.domain.name + ", " +
            obj["operating-system"] + ", " +
            obj["cluster-member-names"] + ", " + obj.uid;
    }
}

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 is the best way to remove words from an object's value that begin with a specific keyword using JavaScript?

Here is a sample array. I need to remove the words row-? from the className property. [ { type: "text", name: "text-1632646960432-0", satir: "1", className: "form-control col-lg-3 row-1" }, { ...

Scrolling to specific ID scrolls only in a downward direction

I have been using fullpage.js for my website and I am facing an issue. When I create a link and connect it to an id, everything works perfectly. However, I am unable to scroll back up once I have scrolled down. Here is the HTML code: <a href="#section ...

Could not parse JSON after php file update. Everything was fine before switching to PDO, but now encountering a parsing issue

I encountered an issue where I could log in using a member from the database (MySQL) using Chrome, and create a new user successfully. However, when I tried to use the app, it crashed after attempting to create a new user. After testing some simple PHP co ...

Sending reference variable from Angular input type=file

I am currently learning Angular and I have implemented a feature where a list of PDF files is displayed using an array called pdfs. In my template, these PDF files are parsed into "card" elements for better visualization. The issue arises when I attempt ...

Events related to SVG elements

I have a unique situation where a div containing multiple SVG elements that act as buttons is added to the page after the user interacts with it. I am trying to add events to these SVG elements using event delegation, where I inspect the target of the even ...

A JSON parsing tool that accepts a string reference and converts it into a JsonObject

When Java passes a string to a function, it is passed by value rather than by reference. For further information on this, click here. getKeyValue(String o); // This creates a new string and passes it by value Class A { String o; } A a; getKeyValue(A ...

combine several arrays next to each other based on a specified key

I have a collection of three sets, each containing three elements: Set1 = [[apple, 2, 4], [banana, 5, 5], [cherry, 4, 1]] Set2 = [[banana, 1, 7], [cherry, 3, 8], [date, 5, 4]] Set3 = [[apple, 5, 2], [banana, 0, 9], ...

Is there a way to make the console output more visually appealing with some styling?

What techniques do programs such as npm and firebase use to generate visually appealing and informative console output during command execution? Consider the following examples: $ firebase deploy or $ npm i <some-package> ...

The Material UI Rating Component is malfunctioning and showing an incorrect value

I'm currently working on a component loop that takes in async data. Everything is rendering properly except for the first component, where the Rating component isn't displaying its value correctly (it just shows 0 stars). Here's the code: & ...

What is the best way to automatically select a checkbox when using ng-repeat on page

I'm looking to automatically check an input checkbox when the page loads, and if it's checked, subtract its value from the total. How can I tackle this issue? Here's the HTML snippet: <p>{{vm.TOTAL VALUE}}</p> <tr ng-repeat= ...

Utilize React-router to display child components on the webpage

Recently, I've encountered some challenges with this code. I have a component that takes in a child as a prop, which is meant to serve as the foundation for all the pages I am hosting. Base.jsx : import React from 'react'; import PropTypes ...

Building a dynamic webpage using AJAX, MVC, and web APIs to generate a div element filled

I'm currently working with a restful API, MVC, and ajax. My goal is to retrieve data from the backend and then display images within certain div elements. The expected outcome should resemble this example: https://i.stack.imgur.com/BFqWL.png This sni ...

Enhancing Material-UI component [TreeView] with drag and drop functionality using react-dnd

I have encountered an issue with my TreeView implementation. Whenever I try to drag and drop a TreeItem, all of its child TreeItems move along with it. Is there a way to enable drag'n'drop functionality for just one TreeItem without affecting its ...

Leveraging data within Gatsby to dynamically generate and display content

I am encountering a problem as a newcomer to Gatsby. In my EventsContainer, I have an UpcomingEvent component where I need to render specific data only when upcomingEvent is true. While I successfully utilized map for EventCard, I'm struggling to do t ...

Verify if the JSON response contains any data

When the JSON response is empty and viewed in the browser console, it appears like this: {"data":{},"status":200,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"http://url/form/BN217473" ...

Is there a way to upload multiple files using expressjs?

I'm looking for a way to efficiently send multiple files, including an entire directory, so that I can access them in another JavaScript file called from an HTML file. const app = require("express")(); const http = require("http"). ...

Values in Local Storage are not located upon first attempt, but after a reload they function properly

import {useEffect} from 'react'; import {useRouter} from 'next/router'; const AuthenticationGuard=props=>{ const {children,fallback} = props; const auth = useAuth(); const router=useRouter(); useEffect(()=>{ if(!r ...

Adjust the TextArea content according to the quantity of selections made in the listbox

If I have a listbox alongside a textarea: <textarea id="MyTextArea"></textarea> <select id="SelectList" multiple> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="me ...

Deciphering the evolution of APIs and managing internal API systems

I'm currently exploring the world of APIs and I have a few questions that are puzzling me. Question1: I understand that APIs facilitate communication between different applications. But why would a company need an API for internal use? For example, i ...

Encountering NPM install gyp errors in VSCode indicating that gyp is searching for Visual Studio

Running npm install on a local project has been quite challenging for me, as I keep encountering errors every time I try. Fortunately, some valuable information I found related to gyp and Python helped me make some progress. However, I'm currently fac ...