Exploring the art of JSON interpretation within Highcharts

Below is an example snippet that utilizes static data:

Highcharts.chart("container", {
  title: {
    text: "Highcharts pie chart"
  },

  xAxis: {
    categories: [
      "Jan",
      "Feb",
      "Mar",
      "Apr",
      "May",
      "Jun",
      "Jul",
      "Aug",
      "Sep",
      "Oct",
      "Nov",
      "Dec"
    ]
  },

  series: [
    {
      type: "pie",
      allowPointSelect: true,
      keys: ["name", "y", "selected", "sliced"],
      data: [
        ["January", 105],
        ["February", 400],
        ["March",230]
      ],
      showInLegend: true
    }
  ]
});
@import "https://code.highcharts.com/5/css/highcharts.css";
.highcharts-series .highcharts-point-select {
  fill: #fff;
  stroke: #f00;
  stroke-dasharray: 10;
}
<script src="https://code.highcharts.com/5/js/highcharts.js"></script>
<div id="container"></div>

Now, I am attempting to parse data from a JSON query with the following format:

{"headers":["Month","Clicks"],"rows":[["January",105],["February",400],["March",230]]}

The current JSON format in the working snippet looks like this:

["January", 105],
["February", 400],
["March",230]

I have encountered difficulties when trying to parse the data correctly. In the updated snippet below, I have added a JavaScript function at the start to parse the JSON data.

var unformatted = {"headers":["Month","impressions"],"rows":[["January",124010],["February",545010]]};

var data2 = [];

for (var i = 0; i < unformatted.rows.length; i++) {
    var row = unformatted.rows[i];
    
    data2.push({
        Month: row[0],
        Clicks: row[1]
    });
}

Highcharts.chart("container", {
  title: {
    text: "Clicks per Month"
  },

  xAxis: {
    categories: [
      "Jan",
      "Feb",
      "Mar",
      "Apr",
      "May",
      "Jun",
      "Jul",
      "Aug",
      "Sep",
      "Oct",
      "Nov",
      "Dec"
    ]
  },

  series: [
    {
      type: "pie",
      allowPointSelect: true,
      keys: ["name", "y", "selected", "sliced"],
      data: data2,
      showInLegend: true
    }
  ]
});
@import "https://code.highcharts.com/5/css/highcharts.css";
.highcharts-series .highcharts-point-select {
  fill: #fff;
  stroke: #f00;
  stroke-dasharray: 10;
}
<script src="https://code.highcharts.com/5/js/highcharts.js"></script>
<div id="container"></div>

Answer №1

To begin, you must first access the initial row and then extract the information from each element in that particular array.

categories: unformatted.rows[0].map(record => record[0])

The information simply consists of the rows themselves.

data: unformatted.rows

// Obtaining an array containing unique items.
const unique = list => [...new Set(list)];

var unformatted = {
  "headers": ["Month", "impressions"],
  "rows": [
    ["January", 124010],
    ["February", 545010]
  ]
};

Highcharts.chart("container", {
  title: {
    text: "Clicks per Month"
  },
  xAxis: {
    categories: unique(unformatted.rows[0].map(record => record[0]))
  },
  series: [{
    type: "pie",
    allowPointSelect: true,
    keys: ["name", "y", "selected", "sliced"],
    data: unformatted.rows,
    showInLegend: true
  }]
});
@import "https://code.highcharts.com/5/css/highcharts.css";
.highcharts-series .highcharts-point-select {
  fill: #fff;
  stroke: #f00;
  stroke-dasharray: 10;
}
<script src="https://code.highcharts.com/5/js/highcharts.js"></script>
<div id="container"></div>

Answer №2

Instead of looping through the JSON data in your code, why not simply assign your "rows" element to your series.data? This way, you can directly use the data without unnecessary iterations. Here's how you can do it:

var unformatted = {"headers":["Month","impressions"],"rows":[["January",124010],["February",545010]]};

var data2 = [];
//console.log(unformatted.rows);
data2 = unformatted.rows;

Answer №3

The error occurred in the data2.push section

// You originally had
data2.push({
    Month: row[0],
    Clicks: row[1]
});

// The correct way is
data2.push([row[0], row[1]]);

Below is the revised version of the code

var unformatted = {"headers":["Month","impressions"],"rows":[["January",124010],["February",545010]]};

var data2 = [];

for (var i = 0; i < unformatted.rows.length; i++) {
    var row = unformatted.rows[i];
    
    data2.push([row[0], row[1]]);

}

Highcharts.chart("container", {
  title: {
    text: "Clicks per Month"
  },

  xAxis: {
    categories: [
      "Jan",
      "Feb",
      "Mar",
      "Apr",
      "May",
      "Jun",
      "Jul",
      "Aug",
      "Sep",
      "Oct",
      "Nov",
      "Dec"
    ]
  },

  series: [
    {
      type: "pie",
      allowPointSelect: true,
      keys: ["name", "y", "selected", "sliced"],
      data: data2,
      showInLegend: true
    }
  ]
});
@import "https://code.highcharts.com/5/css/highcharts.css";
.highcharts-series .highcharts-point-select {
  fill: #fff;
  stroke: #f00;
  stroke-dasharray: 10;
}
<script src="https://code.highcharts.com/5/js/highcharts.js"></script>
<div id="container"></div>

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

Validating date inputs with ng-change in AngularJS

I am currently utilizing AngularJS along with AngularJS bootstrap within my webpage. One of the components I have is a date picker directive that is structured like this: <div class="form-group {{dateStatus.class}}"> <p class="input-g ...

Retrieve the values of a particular key from your Django queryset JSON data and then seamlessly send them over to VueJS

I recently developed a web app using Django2 with Vue for the frontend. I encountered an issue in passing all values of a specific key from JSON data to a JavaScript dictionary value on the frontend. Despite trying to use the += operator to add the data, I ...

Retrieving information from MongoDB queries using Node.js

I am facing an issue while trying to retrieve data from the find() method and use it outside the method. My goal is to incorporate this data into a JSON response. Unfortunately, my current code is not working as expected and the data is not accessible outs ...

The function window.close() does not close the pop-up window when called within the pop-up

I am facing an issue with a Customer Info form that contains an anchor tag "close" meant to close the current window. This customer form is displayed as a pop-up. Within this form, there is also a search button that triggers a pop-up for the search form co ...

Generate a four-dimensional array populated with the data retrieved from an Ajax request

In my JavaScript code, I have an array that looks like this: var data = [ { y: '2017-01', a: 50, b: 90, c:110}, { y: '2017-02', a: 65, b: 75, c:120}, { y: '2017-03', a: 50, b: 50, c:10}, ...

Creating a central navigation menu for a website

Currently, I am working on incorporating a menu in the center of a webpage (please note that this is not a top navigation menu). Here is the initial setup: https://i.sstatic.net/3arql.png Users are able to click on various menu items to access different ...

Customizing CSS to override Semantic React UI styles

Is there a way to customize the default Header provided by react semantic UI? Currently, I have placed my Header within a div so that I can apply custom styles. <div className="portfolioTitle"> <Header as="h1">Check out this amazing ...

struggling with managing an array of Vue3 refs

Having an issue with handling vue3 refs, specifically when retrieving data from Firestore. When logging the [documents], everything seems to work fine. However, I run into errors when trying to access values from an array within a document. For example, ...

Toggle between classes by clicking on the next or back button

Looking to create a multi-step form where the initial step is visible while the rest are hidden using the "hide" class. I want to toggle visibility of each step with Next and Back buttons, displaying only one step at a time. Can someone assist with this? ...

Regex fails to recognize repeated instances of a specific pattern

Currently, my goal is to create a JavaScript regex that can interpret instances of patterns like \123 and convert them into their corresponding ASCII values. For example, 65 should be replaced with A. If the backslash \ itself needs to be includ ...

Hide the div if the content is empty

Within a div created by the_content, there may be content or it could be null, resulting in an empty div that I want to hide. To address this issue, I attempted to store the content in variable $pageContent. However, upon declaring the variable, it either ...

Checkbox: Customize the appearance of the root element

I am trying to modify the root styles of a Checkbox component, but it is not working as expected. Here is my code: <CheckboxItem onChange={()} checked={isChecked} label="Show Checkb ...

Having trouble getting req.files to work in a Node.js Express application?

Hello there, I'm facing an issue with accepting an uploaded file. Every time I call req.files, it comes out as undefined. I can't seem to figure out what I am doing wrong... Below is a snippet of my app.js file: var express = require('expr ...

Material UI causing animation to fail to trigger

After integrating material UI into my existing application, I encountered a peculiar issue. When adding material UI components to modals, the entering animation fails to trigger. Interestingly, downgrading material UI or removing all MUI components resolve ...

Choose only ul elements up to a specific level of depth

ul, ul ul, ul ul ul { list-style: none; margin: 0; padding: 0; } Inquiry: Is there a specific selector that I can utilize to apply styles to every nth level of ul? For instance: ul > ul ...

Verify the status of the nested reactive forms to determine if the child form is in a dirty state

I am working on a form that consists of multiple sections within nested form groups. I need to find a way to detect when changes are made in a specific section. Here is the HTML structure: <div [formGroup]="formGroup"> <div formGroupN ...

Arranging elements on a website using CSS styling

I'm interested in creating a button <Button id="Button" text="Hey" />. I would like to know how I can position it on a webpage exactly where I want it, rather than it just appearing randomly without content. ...

Looking to conceal a JavaScript file or minimize it from the web browser following production build in React

Upon executing the npm run build command using the script provided in my React App's package.json file, "scripts": { "start": "react-scripts start", "build": "set 'GENERATE_SOURCEMAP=false&apos ...

The data input from the HTML is not being correctly transferred to the modal

I am trying to transfer the reservation id from an HTML element to a modal window. When I click "cancel" next to a reservation, a modal should appear showing the reservation id. However, the modal pops up without displaying the reservation id. Can anyone h ...

Ensuring WCAG Accessibility Compliance - mandate the inclusion of at least one input in a fieldset

I'm working on a form where users need to provide at least one contact method from a group of fields, such as home, work, or mobile phone number. How can I ensure this meets the latest WCAG 2.2 standards? <!-- Other fields above and below --> ...