From organizing nested arrays in jSon to visualizing data with D3js

I am completely new to working with d3 and JSON. I have a piece of data from JSON that I am attempting to extract, and I'm wondering if I am headed in the right direction.

My goal is to display a rectangle graph for each server within different status groups, positioning them nicely next to each other.

Despite reading numerous tutorials and searching for similar issues faced by others, I haven't had much luck so far...

The JSON data I am trying to extract:

[
{
    "status": "ok",
    "servers":
            [
                {
                    "id": "VR01",
                    "servername": "Server_1",
                    "cpu": 45, 
                    "mem": 25,
                    "diskIO": 0, 
                    "bandwith": 200
                }

            ]
},
{
    "status": "attention",
    "servers":
            [
                {
                    "id": "VR10",
                    "servername": "Server_10",
                    "cpu": 55, 
                    "mem": 35,
                    "diskIO": 1, 
                    "bandwith": 2000
                 }
            ]

},
{
    "status": "warning",
    "servers":
            [
                {
                    "id": "VR02",
                    "servername": "Server_02",
                    "cpu": 98, 
                    "mem": 85,
                    "diskIO": 1,
                    "bandwith": 2000
                 }
            ]

},
{
    "status": "dead",
    "servers":
            [
                {
                    "id": "VR20",
                    "servername": "Server_20",
                    "cpu": 0, 
                    "mem": 0,
                    "diskIO": 0,
                    "bandwith": 0
                 }
            ]

}

The D3 code snippet:

<script> 

      var width = 1000;
      var height = 800;

    d3.json("mydata.json", function(data) {

        var canvas = d3.select("body").append("svg")
             .attr("width", width)
             .attr("height", height);

      var status = function sortData(d){

          for (i = 0; i < d.length; i++) {

                if(d.status ==="ok") {
                    canvas.selectAll("rect")
                    .data(d.servers)
                    .enter()
                        .append("rect")
                        .attr("x", 25)
                        .attr("y", function(d, i){return 25 * i;})
                        .attr("fill", "purple");
                  }

              }

          });
    </script>          

Any suggestions or guidance would be greatly appreciated!

Answer №1

In my opinion, nesting selections would enhance the way you can design your dashboard.

// To start, create a group for each server group
var serverGroup = svg.selectAll('g')
   .data(data)
   .enter()
   .append('g')
   .attr('transform', function(d, i) { return 'translate(0, ' + 50 * i + ')');

// Next, populate each group with individual elements
var servers = serverGroup.selectAll('rect')
    .data(function(d) { return d.servers; })
    .enter()
    .append('rect')
    // Additional settings can be included here

This approach will result in three distinct groups representing each set of servers, with a vertical shift applied to each one. Each group holds specific data, allowing for customized element creation within each one. Furthermore, by utilizing this structure, you have the flexibility to implement titles, background colors, and other configurations for each group. For further insights, I recommend exploring the article on selection concepts found here: How Selections Work. Best regards,

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

obtaining Json format from an array: a comprehensive guide

Hey there, I am looking to convert my array into JSON format. Currently, my array structure looks like this: Array[0] abc: Array[1] 0: "English" length: 1 abc1: Array[2] 0: "English" 1: "Urdu" length: 2 Here is the structure that I want in JSON using Jav ...

Enhance nested models within a Rails API

I am interested in constructing a Rails API that can create nested records within the database. My goal is to send data to the database for a model associated with a has_many relationship. Is this the correct approach, or are there alternative methods for ...

Exploring the process of iterating through arrays within an object in vue.js using the v-for directive

Is there a way to iterate through an output object using the v-for template in Vue.js? new Vue({ el: app, data: { output: { player: [1, 5, 61, 98, 15, 315, 154, 65], monster: [14, 165, 113, 19, 22], }, }, }); <script src= ...

Value of type 'string' cannot be assigned to type '{ model: { nodes: []; links: []; }; }'

I am a beginner in TypeScript and I have added types to my project. However, I am encountering an error with one of the types related to the graph: Type 'string' is not assignable to type '{ model: { nodes: []; links: []; }; }'.ts(2322) ...

Incorporating a javascript library or plugin into Vue.js code

Hey there, I recently came across the really cool component called vue-social-sharing. It's my first time using a library like this and I'm a bit confused on how to set it up properly. I've installed it through NPM, but when it comes to the ...

method for retrieving a single key-value pair from a JSON object

Suppose I receive a JSON object from the server using var oSer = new JavascriptSerializer(); var sJson = oSer.Serialize(myObject); The JSON returned to the client through an AJAX call is: "{\"IsValid\":false,\"EmployeeId\":null,&bsol ...

What is the best way to eliminate the nesting in this ternary operation?

Object.values(filter).filter(item => (Array.isArray(item) && item.length > 0) || (typeof item === "boolean" && item === true) || (item !== null)).length ? filterIcon : unFilledIcon In this code, I aim to simplify the nested ternary operator and ...

Selecting an entire row in a Kendo grid

Is there a way to configure kendoGrid to highlight the entire row when clicked on? I have tried setting: scrollable: { virtual: true } and disabled paging, but it doesn't seem to work as intended. You can view an example here: Kendo UI Dojo When ...

Standardizing URLs with ExpressJS router

Seeking normalized/canonical URLs for a single page application running on an ExpressJS server. While the SPA is supported by a server-side router, templates can vary slightly for different app URLs. One particular difference is the presence of the <li ...

How to retrieve the value from an editable td within a table using Jquery

I am working with a dynamic table that looks like this: <table> <tbody> <tr> <td>1</td> <td contenteditable='true'>Value1</td> </tr> <tr> ...

Preventing sensitive user passwords from being exposed in JSON responses in Symfony 3

I've run into an issue while developing a Symfony app with an integrated REST API. When I make an API request to return a user entity as JSON, it includes the encrypted user password in the response. While the password is encrypted, I still want to av ...

The JSON file is missing when running the npm v3.10.8 "npm start" command

Encountered an error while trying to start the npm. It appears that the json file cannot be found. Please review the details below along with the log file. simplymacs-MacBook-Air-2:hackoregon_component_library MelissaKeith$ npm "start" npm ERR! Darwin 15. ...

Incorporating animation effects in ajax technology

I've coded a feature that utilizes the .getJSON API from jQuery to retrieve images from the Flickr public API. You can view it on this link. Each image slides after every request is completed. Now, I would like the initial set of images to slide downw ...

The Toggle Functionality necessitates a double-click action

I'm currently working on implementing a menu that appears when scrolling. The menu consists of two <li> elements and has toggle functionality. Everything is functioning properly, except for the fact that the toggle requires two taps to activate ...

Error: The function gethostname has not been declared

I attempted to set a variable using gethostname() (1) and with $_SERVER(2), but I always receive an error message saying ReferenceError: gethostname is not defined. My goal is simply to fetch the current system name into a variable using JavaScript within ...

Web Page Content Scrambling/Character Exchange

I've encountered a perplexing issue that seems to strike randomly, yet I've managed to replicate the problem on three different desktops. Oddly enough, some other desktops never experience this issue and I'm at a loss as to what could be cau ...

import jQuery into a JavaScript file

I'm currently working on a Chrome extension that relies on background.js to perform basic tasks. I need to include jquery.js in my background.js file so that I can utilize its ajax function, but I'm unsure of how to achieve this. Is it even possi ...

Automated algorithm inspecting a variety of hyperlinks

Recently, I've developed an innovative anti-invite feature for my bot. However, there seems to be a minor glitch where the bot fails to remove any links sent within the enabled guild when the command is triggered. This issue specifically occurs in ver ...

Tips for sending JSON information

My Android platform requires me to send a large amount of JSON data to a server. I am considering whether it would be beneficial to split the data into smaller packets or send it all at once. Additionally, I am wondering if running the sending code in a ...

Experiencing difficulties when attempting to show or hide elements using jQuery

I spent several hours trying to figure this out and couldn't get it right. Is it feasible to create a jQuery script that will perform the following action when a <span> element is clicked: Check if any of the <p> elements are current ...