What is the best way to tally the number of fields in a JSON file based on their values

I'm relatively new to JavaScript and have a question that may seem basic. I've been struggling to find the answer, possibly because I'm not using the correct terminology.

My goal is to count the number of "active" fields in a JSON file that are set to true versus false, and then store those values in a variable. I'm finding it challenging to figure out how to approach this task.

Here's an example of my JSON data, which I've named data:

{
"systems": [
    {
        "name": "SV001",
        "IP": "10.1.1.101",
        "active": "true"
    },
    {
        "name": "SV002",
        "IP": "10.1.1.102",
        "active": "true"
    },
    {
        "name": "SV003",
        "IP": "10.1.1.103",
        "active": "false"
    }
]}

I would greatly appreciate any assistance with this issue. Thank you!

Answer №1

To convert a JSON string into a JavaScript object, you can use the following code snippet:

var jsonObject = JSON.parse(jsonString);
Then, by traversing through the object using a loop, you can access its values.

var count = 0;
for (var i = 0; i < jsonObject.systems.length; i++) {
  if (jsonObject.systems[i].active) {
    count++;
  }
}

You will have the total count at the end of the loop.

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

issue arising from integrating material-ui components with code in a react javascript application

Struggling with integrating code and material-ui components in react jsx, I encountered an issue. Here's the problematic snippet: const icols = 0; const makeTableRow = ( x, i, formColumns, handleRemove, handleSelect) => <TableRow key ...

Error: Unable to access attributes of an undefined object (specifically 'headers') in the Next.js evaluation

I encountered an issue with next js TypeError: Cannot read properties of undefined (reading 'headers') at eval (webpack-internal:///(sc_server)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:254:61) Snippet of the pro ...

Adding a JSON array to all JSON objects in JavaScript: A step-by-step guide

Here is a JSON Object that I am working with: { "status": "CREATED", "overrides": { "name": "test_override" }, "package_name": "test", "name": "app1", "defaults": { "job": { "example": { "executors_num": "2", "fr ...

Obtaining a response in string format using the $.ajax function

var module = (function(){ return{ loadData: function(url, success, error){ $.when($.ajax({ type: 'GET', cache: false, url: url, contentType: 'application ...

No Angularjs redirection without the "onload" event

In my search for a solution, I came across this answer but it did not quite fit my needs: Pass onload event through redirect The issue I'm facing is that I want the AngularJS section of my application to reload something when the user is redirected ...

Querying data in JSON using LINQ's dynamic method

Method with a variable that can accept various JSON structures to be queried over LINQ... Currently, my result is moving in the right direction by returning the selected results over the LINQ query but it's statically coded. I have multiple sets of ...

Is there a syntax error in Javascript when using a string and variable with the GET method?

Is there a way to send a value using the get method? In JavaScript, we need to use the + symbol to concatenate strings. But my issue goes beyond this simple problem. If I attempt the following: Let's say; var sID = 16; var rID = 17; EDIT-2: I act ...

Encountering a KeyError in Python while manipulating JSON data

I’ve encountered a challenge with my Python program as I work with JSON data. temp = json.loads(text2) data = temp["data"] try: ld = data["all"] globals()['currentbrowserall'] = ld del data["all"] except: s = str(sys.exc_info() ...

Resolve the Prototype_Pollution vulnerability detected by Checkmarx

When executing the code line window.location.search.substring(1) with the word 'substring(1)', an error related to Prototype_Pollution occurs. This error is caused by assigning external properties without proper validation, which can lead to obje ...

Challenges with browsing navigation in Selenium WebDriver

Recently, I began my journey of learning selenium WebDriver. In an attempt to automate the task of logging into an account using the Firefox browser, I encountered a discrepancy. Manually opening the browser and clicking on the login link from the homepag ...

Utilize Next.js with Axios for making an HTTP request to a Laravel Lumen endpoint, then showcase the retrieved data within the Next.js

I currently have a Next.js application that utilizes Axios to make calls to Lumen endpoints. The Axios HTTP client functions are organized in a separate folder named services/index.tsx, with sample code as follows: export const register = async (payload: a ...

Ordering tables in jQuery with both ascending and descending options

Trying to sort a table in ascending and descending order using jQuery? Here's the JavaScript code for it. However, encountering an error: Cannot read property 'localeCompare' of undefined If you can provide guidance on how to fix this so ...

What causes the oninput event to act differently in Angular as opposed to regular JavaScript?

As I delve into learning Angular with TypeScript, I've encountered some inconsistencies compared to JavaScript that are puzzling me. Take for example this function that works flawlessly with pure JavaScript, where it dynamically sets the min and max a ...

Executing javascript whenever a page is updated

Looking for a solution to ensure that my userscript runs every time an AJAX call modifies any page it is attached to. Is there a way to listen for XMLHttpRequests and trigger the script accordingly? ...

Utilizing numerous JSON entities within an AS3 socket

When receiving JSON data from a camera through a Socket, I encountered an issue. The received data contains two JSON objects in the socket. Is there a way to separate them before decoding? This is the error message I receive when trying to decode the J ...

Learn how to showcase LINQ query results in a string array within an ASP.Net MVC view

I am working on integrating a tags input box into my application. After researching, I came across the library available at When it comes to the Controller Create Method: // GET: Posts/Create public ActionResult Create() { var Ta ...

Securely Upload Files with JavaScript

Are there any methods to utilize javascript or ajax for encrypting file uploads securely? If so, could you provide a sample code snippet or direct me to a functional example? ...

Retrieving information from embedded JavaScript code

The web page I am scraping contains inline JavaScript that dynamically generates telephone numbers inside a script tag. These numbers are not visible in the page source, making it challenging to scrape using common methods like x-path and beautiful soup. U ...

Trouble with Ajax call after transitioning from getJSON to Amcharts

Here is the method for making an AJAX call in a JavaScript file to create a bar graph using Amcharts. The script is located in the bar.js file: plot_graph(); function plot_graph(){ $.ajax({ url:back+"/cool?day=30", type: "GET", dataformat ...

Is it necessary to delay until the entire page finishes loading in Selenium 3?

public boolean CheckPageLoadStatus(){ final ExpectedCondition<Boolean> pageLoadCondition = new ExpectedCondition<Boolean>() { public Boolean apply(final WebDriver driver) { return ((JavascriptExecutor) driver).executeScr ...