How to Load JSON Data Using D3 When Column Definitions are Separated

I'm currently working with d3.js and struggling to grasp how I can effectively load a JSON file representing a table that has separate column definitions.

A typical JSON file, which I have no issue loading, might appear like this:

[
{
    "id": 1,
    "name": "A green door",
    "price": 12.50
},
{
    "id": 2,
    "name": "A red door",
    "price": 12.50
},
{
    "id": 3,
    "name": "A blue door",
    "price": 12.50
}
]

On the other hand, a JSON file with separated columns would look something like this:

{
    "columns": [
        {
            "ColumnName":"id",
            "DataType":"number"
        },
        {
            "ColumnName":"name",
            "DataType":"string"
        },
        {
            "ColumnName":"price",
            "DataType":"number"
        }
    ],
    "rows": [
        [
            "1",
            "A green door",
            "12.50"
        ],
        [
            "2",
            "A red door",
            "12.50"
        ],
        [
            "3",
            "A blue door",
            "12.50"
        ]
    ]
}

Is there a way for d3.js to directly load this type of JSON without needing to modify its structure?

Unfortunately, the original format of the JSON data cannot be altered.

Your assistance is greatly appreciated.

Answer №1

If you're dealing with JSON data in separated columns (Format 2) and using d3, there's a simple solution to ensure smooth loading. After loading the JSON, all you need to do is convert the format to match your desired d3 layout. Here's some sample code to help you out:

d3.json("path/to/column_json_file_name.json", function(error, data) {
  if (error) return console.warn(error);
  var columns = data.columns.map(function(d){ return d.ColumnName });
  var jsonInRquiredFormat = data.rows.map(function(row,i){ 
      var ob = {}; 
      ob[columns[0]] = parseInt(row[0]); 
      ob[columns[1]] = row[1]; 
      ob[columns[2]] = parseFloat(row[2]); 
      return ob; 
  });
  console.log(jsonInRquiredFormat);
});

Here's an example of the output you can expect from the provided code snippet:

[{
    "id": 1,
    "name": "A green door",
    "price": 12.5
}, {
    "id": 2,
    "name": "A red door",
    "price": 12.5
}, {
    "id": 3,
    "name": "A blue door",
    "price": 12.5
}]

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

Uploading files with node.js and express

Currently, I am following the steps outlined in this tutorial: I have successfully followed the instructions until the section where they set up the routes without actually creating any views. The tutorial states: That's it, we have completed sett ...

Tips for sending a Json POST request using Java with Blitline

Hello everyone, I'm currently facing an issue while attempting to send a Json POST request in Java for utilizing the image processing service Blitline. Each time I try, I encounter the following error: IOException: Server returned HTTP response code: ...

Save the file to a specific folder and compress the entire folder into a

I have encountered an issue while attempting to write a file to a directory named templates and then stream a zip file with the content that was just written. The problem arises when the zip file is returned, displaying an error message "Failed - Network E ...

The Notebook Unreadability Issue arises with an error message indicating that the notebook does not seem to be in JSON format: u'{ "cells": [ { "cell_type": "...',

Encountering a peculiar error while trying to load my ipython notebook. This error is new to me, and I cannot recall doing anything out of the ordinary with ipython: Unreadable Notebook: /path/to/notebooks/results.ipynb NotJSONError('Notebook does no ...

Enabling and disabling contenteditable functionality on a div element in Angular

Issue I am facing an issue while trying to bind a boolean to the contenteditable directive of a div. However, it seems that this binding is not working as expected. Error Message: The 'contenteditable' property is not recognized as a valid p ...

Having trouble displaying information in a table using React JS

I devised a feature to display one column of a table and one column for checkboxes (each row should have a checkbox). I stored this file in a component folder with the intention of creating a page where the user selects an account type, and then a new tabl ...

Organize Javascript objects based on their dates - group them by day, month,

I've scoured the internet for examples but haven't found a suitable one that accomplishes the simple task I need. Maybe you can assist me with it. Here is an array of objects: [ { "date": "2015-01-01T12:00:00.000Z", "photoUrl": "", ...

React is nowhere to be seen

index.js: import react from 'react'; import {render} from 'react-dom'; render( <h1>Hello World!</h1>, document.getElementById('root') ); package.json: { "name": "", "version": "1.0.0", "descriptio ...

"Exploring the power of Angular's translation capabilities paired with

I'm currently working on translating a multistep form using Angular Translate and routing with ui-router. Everything seems to be functioning properly except for one issue. Below is the snippet of my code: Translation Setup: .config(function ($t ...

The issue of `for` loop and `forEach` loop not functioning in EJS

I'm currently developing a To-Do App and facing difficulty with the POST request functionality. I've attempted using both a for loop and a forEach loop but none seem to be working. <% todos.forEach(item => { %> <li><%= item ...

using the java api for elasticsearch to implement compound queries

Can someone please provide guidance on creating a compound query for finding geojson data with specific properties within a polygon? I am aware of the GeoPolygonQueryBuilder and BoolQueryBuilder in Elasticsearch, but how can they be used together in one re ...

New feature in jQuery inputmask enables placeholder text to be retained

I have integrated the inputmask feature from https://github.com/RobinHerbots/jquery.inputmask in my project, and I am applying the mask to all textboxes with the class "date". However, I am encountering a problem where if the user leaves one or more letter ...

Ways to stop the react-router from causing the page to refresh

Need assistance with React Router issue I'm working on a project in reactJs using react-router-dom v5. I have set up a default route for routing. <Redirect to={"someComponent"}/> The problem is that when I refresh the page, it auto ...

divide an array into two separate arrays depending on whether the index position is odd or even

Here is an example array: Arr1 = [1,1,2,2,3,8,4,6]. I'm trying to divide this array into two new arrays based on the odd or even position of elements. Can anyone provide a solution? New Array 1 (odd positions): [1,2,3,4] New Array 2 (even positions) ...

Handling errors in XMLHttpRequest using Axios in React JS

I am currently utilizing the REACT-JS framework for my FRONT-END development: Below is the action I am calling from REDUX-REACT export function UserLogin(values) { var headers = { 'Access-Control-Allow-Origin': '*', ...

Looping through color transitions upon hover using CSS

I am trying to create a color transition effect on hover, where the background changes from yellow to red and then back to yellow in a loop. I'm having trouble figuring out how to make this transition repeat continuously. Do I need to incorporate Java ...

inject the HTML content into the <div> container

Snippet: https://jsfiddle.net/x9ghz1ko/ (Includes notes.) In my HTML file, there are two distinct sections: <section class="desktop_only"> and <section class="mobile_only">. The challenge lies in positioning a JavaScript sc ...

Error encountered in Bootstrap 5: Popper__namespace.createPopper function is not defined

Currently using Django to host web pages. Focus is on enabling offline access by downloading all necessary resources to ensure webpage functionality, like Bootstrap 5. Attempting to utilize the dropdown menu feature in Bootstrap: Dropdowns depend o ...

Having difficulty in effectively deleting a D3 element

I am facing an issue with removing and replacing a bar chart using the remove method in D3. When I use the remove() function on the selection, the SVG content disappears leaving only the empty SVG element visible in the DOM, taking up space on the screen. ...

Retrieve information from a JSON file according to the provided input

Can someone help me fetch data based on user input in JavaScript? When the input is 'Royal Python', I'm supposed to retrieve details about it. However, the code provided gives an error stating 'The file you asked for does not exist&apo ...