Access an object value within a JSON response

My task is to extract servlet details from the JSON response received from our servers. Here is a snippet of the JSON data:

if(dataStoreLogFileSize > 10 && "dataStoreLogLevel": "production".)

I've attempted to parse the data using the following JavaScript code, but it's not functioning correctly. Any assistance on this issue would be greatly appreciated.

{
"web-app": {
    "servlet": [{
            "servlet-name": "cofaxCDS",
            "servlet-class": "org.cofax.cds.CDSServlet",
            "init-param": {
                // Parameters here
            }
        },
        {
            "servlet-name": "cofaxTools",
            "servlet-class": "org.cofax.cms.CofaxToolsServlet",
            "init-param": {
                // More parameters here
            }
        }
    ],
    "servlet-mapping": {
        // Servlet mappings here
    },

    "taglib": {
        // Taglib information here
    }
  }
}

+********************************************************************************+

//Some code above

let foo = data.filter(object => (object.dataStoreLogLevel === 'production'
                      && object => (object.dataStoreLogFileSize > '10');
console.log('Servlet Details Test' + foo);

//Code continues 

Answer №1

This code snippet will help you filter out dataStoreLogFileSize greater than 1GB and with a production dataStoreLogLevel.

const jsonData = {
  "web-app": {
servlet: [
  {
    "servlet-name": "cofaxCDS",
    "servlet-class": "org.cofax.cds.CDSServlet",
    "init-param": {
      "configGlossary:installationAt": "Philadelphia, PA",
      "configGlossary:adminEmail": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f19a829cb1819e939e89df929e9c">[email protected]</a>",
      "configGlossary:poweredBy": "Cofax",
      "configGlossary:poweredByIcon": "/images/cofax.gif",
      "configGlossary:staticPath": "/content/static",
      templateProcessorClass: "org.cofax.WysiwygTemplate",
      templateLoaderClass: "org.cofax.FilesTemplateLoader",
      templatePath: "templates",
      templateOverridePath: "",
      defaultListTemplate: "listTemplate.htm",
      defaultFileTemplate: "articleTemplate.htm",
      useJSP: false,
      jspListTemplate: "listTemplate.jsp",
      jspFileTemplate: "articleTemplate.jsp",
      searchEngineListTemplate: "forSearchEnginesList.htm",
      searchEngineFileTemplate: "forSearchEngines.htm",
      searchEngineRobotsDb: "WEB-INF/robots.db",
      useDataStore: true,
      dataStoreClass: "org.cofax.SqlDataStore",
      redirectionClass: "org.cofax.SqlRedirection",
      dataStoreName: "cofax",
      dataStoreDriver: "com.microsoft.jdbc.sqlserver.SQLServerDriver",
      dataStoreUrl:
        "jdbc:microsoft:sqlserver://LOCALHOST:1433;DatabaseName=goon",
      dataStoreUser: "sa",
      dataStorePassword: "dataStoreTestQuery",
      dataStoreTestQuery: "SET NOCOUNT ON;select test='test';",
      dataStoreLogFile: "/usr/local/tomcat/logs/datastore.log",
      dataStoreInitConns: 10,
      dataStoreLogFileSize: "1GB",
      dataStoreMaxConns: 100,
      dataStoreConnUsageLimit: 100,
      dataStoreLogLevel: "production",
      maxUrlLength: 500
    }
  },
  {
    "servlet-name": "cofaxTools",
    "servlet-class": "org.cofax.cms.CofaxToolsServlet",
    "init-param": {
      templatePath: "toolstemplates/",
      log: 1,
      logLocation: "/usr/local/tomcat/logs/CofaxTools.log",
      logMaxSize: "",
      dataLog: 1,
      dataLogLocation: "/usr/local/tomcat/logs/dataLog.log",
      dataLogMaxSize: "",
      removePageCache: "/content/admin/remove?cache=pages&id=",
      removeTemplateCache: "/content/admin/remove?cache=templates&id=",
      fileTransferFolder:
        "/usr/local/tomcat/webapps/content/fileTransferFolder",
      lookInContext: 1,
      adminGroupID: 4,
      betaServer: true,
      dataStoreInitConns: 10,
      dataStoreLogFileSize: "0.5GB",
      dataStoreMaxConns: 100,
      dataStoreConnUsageLimit: 100,
      dataStoreLogLevel: "test",
      maxUrlLength: 500
    }
  }
],
"servlet-mapping": {
  cofaxCDS: "/",
  cofaxEmail: "/cofaxutil/aemail/*",
  cofaxAdmin: "/admin/*",
  fileServlet: "/static/*",
  cofaxTools: "/tools/*"
},

taglib: {
  "taglib-uri": "cofax.tld",
  "taglib-location": "/WEB-INF/tlds/cofax.tld"
}
  }
};

// Filter the JSON data based on conditions
const filteredData = jsonData['web-app'].servlet.filter((s) => {
  // Extract the size from dataStoreLogFileSize
  const size = s['init-param'].dataStoreLogFileSize.replace(/[^0-9\.]+/g, '');
  // Check if size is greater than or equal to 1 and has 'production' log level
  return +size >= 1 && s['init-param'].dataStoreLogLevel === 'production';
});

console.log(filteredData);

Answer №2

you are currently filtering the incorrect array, the one containing dataStoreLogLevel and dataStoreLogFileSize can be found in

data['web-app'][0]['servlet']['init-param']
, so you must apply the .filter method on the data['web-app'].servlet array.

When dealing with fileSize, remember to use parseFloat in order to extract the size since it is stored as a string.

The syntax for .filter needs to be corrected.

Make sure to separate values using , when using console.log to display the result :

const data = {
    "web-app": {
        "servlet": [{
                "servlet-name": "cofaxCDS",
                "servlet-class": "org.cofax.cds.CDSServlet",
                "init-param": {
                    "configGlossary:installationAt": "Philadelphia, PA",
                    "configGlossary:adminEmail": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3a5149577a4a5558554214595557">[email protected]</a>",
                    "configGlossary:poweredBy": "Cofax",
                    "configGlossary:poweredByIcon": "/images/cofax.gif",
                    "configGlossary:staticPath": "/content/static",
                    "templateProcessorClass": "org.cofax.WysiwygTemplate",
                    "templateLoaderClass": "org.cofax.FilesTemplateLoader",
                    "templatePath": "templates",
                    "templateOverridePath": "",
                    "defaultListTemplate": "listTemplate.htm",
                    "defaultFileTemplate": "articleTemplate.htm",
                    "useJSP": false,
                    "jspListTemplate": "listTemplate.jsp",
                    "jspFileTemplate": "articleTemplate.jsp",
                    "searchEngineListTemplate": "forSearchEnginesList.htm",
                    "searchEngineFileTemplate": "forSearchEngines.htm",
                    "searchEngineRobotsDb": "WEB-INF/robots.db",
                    "useDataStore": true,
                    "dataStoreClass": "org.cofax.SqlDataStore",
                    "redirectionClass": "org.cofax.SqlRedirection",
                    "dataStoreName": "cofax",
                    "dataStoreDriver": "com.microsoft.jdbc.sqlserver.SQLServerDriver",
                    "dataStoreUrl": "jdbc:microsoft:sqlserver://LOCALHOST:1433;DatabaseName=goon",
                    "dataStoreUser": "sa",
                    "dataStorePassword": "dataStoreTestQuery",
                    "dataStoreTestQuery": "SET NOCOUNT ON;select test='test';",
                    "dataStoreLogFile": "/usr/local/tomcat/logs/datastore.log",
                    "dataStoreInitConns": 10,
                    "dataStoreLogFileSize": "1GB",
                    "dataStoreMaxConns": 100,
                    "dataStoreConnUsageLimit": 100,
                    "dataStoreLogLevel": "production",
                    "maxUrlLength": 500
                }
            },
            {
                "servlet-name": "cofaxTools",
                "servlet-class": "org.cofax.cms.CofaxToolsServlet",
                    ...
          ]
        }
    }
}

let foo = data['web-app'].servlet.filter( 
  object => 
    object['init-param'].dataStoreLogLevel === 'production' 
    && parseFloat(object['init-param'].dataStoreLogFileSize) >= 1 // update this to 10 for fileSize >= 10GB
);

console.log('Servlet Details Test', foo);

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

Grouping JSON data by a specific key is the key to better organization

Assume the JSON data looks like this: $string = '{ "John": { "status":"Wait", "id":"001" }, "Jennifer": { "status":"Active", "id":"002" }, "James": { "status":"Active", "age":56, "count":10, "progress":0.0029857, ...

Add the div id to the script

Currently, I have a script set up where by clicking on a specific div (for example id=packtoa), it will add a class 'show' to listview items that have a matching class with the clicked div's id. While this system works well, I find myself n ...

Deliver varied asset routes depending on express js

I have a situation where I am working with express routes for different brands. My goal is to serve two separate asset directories for each brand route. One directory will be common for all brand routes, located at public/static, and the other will be spec ...

Error in Typescript: Attempting to access the property 'set' of an undefined value

Currently, I am in the process of setting up a basic example of push notifications on Android using Nativescript and Typescript. Although my code may seem a bit messy, I am struggling with properly rewriting "var Observable = require("data/observable");" a ...

Please refrain from refreshing the page multiple times in order to receive updated data from the database

Currently, I have created a countdown timer from 00:60 to 00:00. However, once the timer reaches 00:00, I am looking to refresh the page only once in order to retrieve a new value from the database. Does anyone have any suggestions on how to achieve this ...

Experiencing issues with passwords in nodemailer and node

Currently, I am utilizing nodemailer in conjunction with Gmail and facing a dilemma regarding the inclusion of my password. The predicament stems from the fact that my password contains both single and double quotes, for example: my"annoying'password. ...

Dynamically loading a webpage with an element roster

I have a list and I want it so that when a user clicks on the sport1 list item, results from the database table sport1 will be displayed. Similarly, if they click on the education1 list item, results from the education1 table should be shown. The issue i ...

Can one access the method definition within a Visual Studio Code setup for an AngularJS project?

I'm on a quest to locate the method definition within my AngularJS project, but alas, I am struggling to discover a quick and easy shortcut for this task. My attempts with Ctrl + Click only led me to the initial occurrence of the variable's decla ...

The module "jquery" in jspm, jQuery, TypeScript does not have a default export

Having some trouble setting up a web app with TypeScript and jspm & system.js for module loading. Progress is slow. After installing jspm and adding jQuery: jspm install jquery And the initial setup: <script src="jspm_packages/system.js"></scri ...

"Use casperjs to click on a variable instead of a specific selector

Is there a way to interact with a page element in CasperJS without specifying a selector? For example, instead of using: casperjs.thenClick('#test'); I have the variable: var testV = document.querySelector('#test'); And I would like ...

The modal is not displayed when the on click listener is triggered

I'm a beginner in the world of programming and I'm currently working on creating modals that pop up when clicked. However, I'm facing an issue where the pop-up message doesn't appear when I click the button. Oddly enough, only the overl ...

The deployed MVC code encountered an unexpected token "u" in the JSON at position 0

I have a MVC 5 application that is functioning well in the development environment. However, when I publish and deploy it to the testing server (or any other server), I encounter a JavaScript error when clicking on the login button: Uncaught SyntaxError ...

Connecting a Kendo Dropdown menu to external data sources for seamless integration

I need help with binding data to a dropdown list for my local service. Whenever I try to download the data, I keep getting an error message: Uncaught SyntaxError: Unexpected token: Does anyone have any ideas on how to resolve this issue? This is my JS ...

Add the $scope ng-click event to a previously hidden element once it becomes visible

If you need a clearer explanation, feel free to ask. I have incorporated a global search function into the header of my website. I am looking to show a separate input box for mobile search that utilizes the same ng-click event, but the input field remains ...

Expanding iframe elements

I am having difficulty adjusting the size of the iframe content (within a fixed-sized iframe). Essentially, I would like the content to scale smaller or larger as if the browser's zoom function was being used. Through my CSS experiments, it seems achi ...

What are some effective ways to optimize a scrolling script?

Within my div element, I have a list of ordered elements (ol) that I am manipulating with drag and drop functionality using jQuery Nestable. If you could help me troubleshoot this issue, it would be greatly appreciated: How to scroll the window automatical ...

Is there an Angular counterpart to Vue's <slot/> feature?

Illustration: Main component: <div> Greetings <slot/>! </div> Subordinate Component: <div> Planet </div> Application component: <Main> <Subordinate/> </Main> Result: Greetings Planet! ...

Populating a two-dimensional array with randomly generated numbers using javascript

Apologies if this has been asked before, but I couldn't find any previous posts on the topic as I'm still fairly new to this site! Lately, I've been exploring game development using HTML5 and JavaScript and have gotten into creating tileset ...

"After refreshing the page, the .load() function did not run as

After loading the page and adjusting the viewport size, I am trying to retrieve the dimensions of images. While I can successfully get image dimensions after the page loads using .load, I am struggling to find a way to update the image sizes when the viewp ...

What is the best way to transfer Javascript variables from an HTML template to a view function in Django?

Currently, I am developing a website using Django. One of the features I'm working on is a form in my HTML page that includes a textbox for users to input their name with a label "Enter your name". Underneath the textbox, there is a submit button. ...