Transforming an Excel document into JSON format: inspection of JSON code structure

Looking to transform Excel data into JSON format, but unsure if the current structure will be ideal for processing with D3.js. Planning to incorporate this JSON file within D3.js for visualization purposes.

Here's a snippet of the Excel file:

In the process of converting this dataset into a JSON file to seamlessly integrate with D3.js. Here's a glimpse at what's been achieved so far:

My query is: Is this organization method optimal for utilizing the data effectively with D3.js? Providing a sample output for reference:

Appreciate any insights and guidance!

Answer №1

This question may be subjective, but based on my experience, there is a more effective approach:

If you are using d3, chances are you are implementing something similar to this:

d3.selectAll('div')
  .data(entities)
.enter()
  .append('div')
  ...

The key consideration here is what constitutes your 'entities'. Are they all countries in the world? Or perhaps countries along with regions and the entire world? Alternatively, do your views only display countries within a selected region without including the region itself?

Unless the proposed JSON structure aligns perfectly with how entities are meant to be displayed, you will likely need to manipulate arrays extensively through concatenation and filtering to consolidate them into a single entities array for binding. While this approach might work, it could introduce unnecessary coupling between your code and data structure.

In my experience, maintaining a flat hierarchy, similar to that in an excel file, tends to be the most flexible and straightforward coding-wise. Rather than embedding regions into the hierarchy, keep them in a single, flat array like this:

{
  "immigration": [
    {
      "name": "All Countries"
      "values: [
        { "Year": ..., "value": ... },
        { "Year": ..., "value": ... },
        ...
      ]
    },
    {
      "name": "Africa"
      "values: [
        { "Year": ..., "value": ... },
        { "Year": ..., "value": ... },
        ...
      ]
    },
    {
      "name": "Eastern Africa"
      "continent": "Africa"
      "values": [
        { "Year": ..., "value": ... },
        { "Year": ..., "value": ... },
        ...
      ]
    },
    // More country entries
  ]
}

Despite being flat, this array retains a hierarchical structure via properties like region and sub-region.

To extract desired countries/regions, simple filtering can be employed instead of navigating the proposed hierarchy:

var africanEntities = data.immigration.filter(function(country) {
  return country.continent == "Africa";
}); // Includes the region "East Africa"

var justCountries = data.immigration.filter(function(country) {
  return country.continent != null && country.region != null;
});

In addition, utilizing d3's d3.nest() function can effortlessly transform flat data into a hierarchical format:

var countriesByContinent = d3.nest()
  .key(function(d) { return d.continent; })
  .map(data.immigration);

var africanEntities = countriesByContinent['Africa'];

Hopefully, this provides some clarity...

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 are some ways to streamline this D3 script?

My CSV data displays pass rates by organisation for different years: org,org_cat,2004_passed,2004_total,2005_passed,2005_total,2006_passed,2006_total GSK,industry,35,100,45,100,55,100 I am using D3 and aiming to create a dictionary of organisations struc ...

Empty MongoDB array persists even after POST request

After performing a POST request in Insomnia, my "games" array remains empty. What am I missing? UPDATE: New error after array.push({}) "errorValidationError: games.0.gameID: Path gameID is required., games.0.isGameActivated: Path isGameActivated is requi ...

Whenever the page is refreshed, the props in my application are dynamically updated thanks to the getStaticProps function I utilize

Currently, I am in the process of learning nextjs as a beginner. Through the utilization of the getStaticProps function, I have come to understand that data fetching occurs only once at build time and the values remain static thereafter. Despite this, I ...

Transforming single-to-multiple json files into a csv format

I'm currently facing a challenge in parsing the json output from an API call. The returned data consists of an array of orders, each containing an array of items. My goal is to parse this information in order to generate a single CSV file that include ...

What could be causing my Wikipedia opensearch AJAX request to not return successfully?

I've been attempting various methods to no avail when trying to execute the success block. The ajax request keeps returning an error despite having the correct URL. My current error message reads "undefined". Any suggestions on alternative approaches ...

Is there a specific minimum height that should be set for the equalHeight function to apply?

Despite trying everything, I can't seem to achieve the dreadful layout my designer has given me without using JavaScript! The issue lies with the positioning of the div #backgr-box, which needs to be absolutely positioned behind the #contenuto ( ...

What is the reason behind Firefox failing to display a linear gradient when the background-size values are more than 255px?

I am working on creating a grid overlay using an absolutely positioned non-interactive div. My approach involves using the repeating-linear-gradient property as suggested by others for this purpose. The functionality works smoothly in Chrome, but I seem to ...

Wrap the json response in HTML elements

I'm currently learning about AJAX, and I've encountered a major issue that I can't seem to resolve. I pass several variables to PHP, perform various checks there, and then return string values to AJAX. Strangely, I am able to display these r ...

Angular JavaScript Object Notation structure

I am a beginner in AngularJS and I'm attempting to create formatted JSON based on the values of table rows (tr) and cells (td). The table rows are generated automatically. When the form is submitted, I try to create the JSON values. Once the form is ...

applying the "active" class to both the parent and child elements

Looking for a way to apply an active class to both the parent and child elements when a user clicks on the child element within a list. The HTML structure is as shown below:- <ul class="tabs"> <li class="accordion"><a href="#tab1"> ...

Loading jsp content into a div dynamically within the same jsp file upon clicking a link

Currently, I am working on creating a user account page. On this page, my goal is to display related JSP pages in a div on the right side when clicking links like 'search user' or 'prepare notes' on the left side. In my initial attempt ...

Tips for creating a dynamic route with NextJs 14 API

Looking to start a blog with Next.js 14 and I'm working on defining a function in api/posts/[postSlug]/route.js. How do I access the postSlug parameter within this function? Here's my current function code: // api/posts/[postSlug]/route.js impor ...

Retrieve the property values of `T` using a string key through the `in

Having trouble accessing a property in an object using a string index, where the interface is defined with in keyof. Consider the following code snippet: interface IFilm { name: string; author: string; } type IExtra<T extends {}> = { [i ...

Utilizing a Static Image Path Prop in React JS: A Step-by-Step Guide

My Main Component import React from "react"; import TopModal from "./components/topModal"; // Passing productImage to the Child Component import productImage from "../../../../../../assets/images/juices.jpg"; import { makeS ...

Please use Shift + Enter feature only when using desktop devices

In my React chat application, I have implemented a textarea for message input to allow multiline support. This works smoothly on mobile devices as pressing Enter creates a new line and a send button is available to submit the message. However, I want a di ...

Step-by-step guide to generating a Paypal Button using Vue 3 script setup

After going through the PayPal Developer Docs, I'm still struggling to understand how to integrate the PayPal Button into Vue.js. The code examples provided are unclear, and I can't determine if it's related to Vue 2, Vue 3, or even Angular. ...

Can you guide me on how to simulate key presses using Selenium in VBA specifically for Chrome?

Despite attempting different methods, none of them seem to be effective. Mydoc.FindElementByXPath("/html/body").SendKeys (Space) Mydoc.FindElementByXPath("anyxpath").SendKeys (keys.Space) Mydoc.FindElementByXPath("anyxpath" ...

Angular code isn't functioning properly

I recently started coding in Angular.js using WebStorm: <!DOCTYPE html> <html ng-app="store"> <head lang="en"> <meta charset="UTF-8> <title></title> </head> <body ng-app="store"> <script src="bowe ...

Event not tracking properly due to missing label in GA event firing

Seeking assistance with a project I'm currently engaged in. I have created an HTML5 video containing a playlist and encountering difficulties setting up multiple labels in GA to track each individual video play. While I found code online, adapting it ...

What is the best way to restrict the selection of specific days of the week on an HTML form date input using a combination of JavaScript, React, and HTML?

I need help customizing my Forms Date Input to only allow selection of Thursdays, Fridays, and Saturdays. I've searched for a solution but haven't been successful so far. Is there any JavaScript or HTML code that can help me achieve this? Below ...