Incorporating JSON data seamlessly into a visually appealing Highcharts pie chart

It seems like I'm facing a minor issue here. Everything was working fine until...


$(document).ready(function() {
// Original data
var data = [{
    "name": "Tokyo",
    "y": 3.0
}, {
    "name": "NewYork",
    "y": 2.0
}, {
    "name": "Berlin",
    "y": 3.5
}, {
    "name": "London",
    "y": 1.5
}];
var chart = new Highcharts.Chart({
    chart: {
        renderTo: 'container',
        type: 'pie'
    },
    series: [{
        data: data
    }]
});
});

My attempt to modify the code to load using getJSON with correctly formatted JSON resulted in this...


$(document).ready(function() {
    $.getJSON("etstats?rtype=bestpgs_ec&month=2016-06-01&no_requested=10", function(json){
    var data = json
    var chart = new Highcharts.Chart({
    chart: {
        renderTo: 'container',
        type: 'pie'
    },
    series: [{
        data: data
    }]
  });
 });
});

After checking the JSON in Firebug, it appears to be formatted correctly with "name" and "y" values.


[{"name": "14704", "y": "0.17"}, {"name": "14706", "y": "0.20"}, {"name": "21304", "y": "0.25"}, {"name"
: "23201", "y": "0.39"}, {"name": "23501", "y": "0.42"}, {"name": "17102", "y": "0.46"}, {"name": "15001"
, "y": "0.48"}, {"name": "23002", "y": "0.50"}, {"name": "13201", "y": "0.50"}, {"name": "17401", "y"
: "0.52"}]

Any suggestions on why my chart is not rendering?

Note: Updated to include solution. The quoted values were causing the problem, which is resolved by iterating over them and evaluating the value.


    $.getJSON("etstats?rtype=bestpgs_ec&month=2016-06-01&no_requested=10", function(json){
    data = json
    $.each(data, function (i, point) {
         point.y = eval(point.y);
    });
    var chart = new Highcharts.Chart({

Answer №1

Based on the provided data, it appears that highchart may not accept strings in the "y" parameter.

For a demonstration, you can view the demo here.

A valid JSON format should follow this structure:

[
  {"name":"14704","y":0.17},
  {"name":"14706","y":0.2},
  {"name":"21304","y":0.25},
  {"name":"23201","y":0.39},
  {"name":"23501","y":0.42},
  {"name":"17102","y":0.46},
  {"name":"15001","y":0.48},
  {"name":"23002","y":0.5},
  {"name":"13201","y":0.5},
  {"name":"17401","y":0.52}
]

Ensure to use getJSON and then apply JSON.parse to convert the object correctly before passing it to highchart.

Answer №2

Make sure to verify that your output for getJSON is in JSON format. If it is, you can proceed by performing the following steps:

var data = JSON.parse(json);

Answer №3

This is how I tackled the challenge of updating data on a Pie chart sourced from MySQL using jQuery.

Firstly, in PHP: generate an array comprising arrays with value/name pairs and don't forget to have the data "json_encode"d:

   ... [code] ...
   while($row = mysqli_fetch_assoc($result)){
      $data[] = array("y" => $row['numeric_value'], "name" => $row['label']);
   }
   exit(json_encode($data));

Next, set up the chart:

    graph = new Highcharts.chart({
       chart: {
          renderTo: 'graphid',
       ... [code] ...
       plotOptions: {
          pie: {
       ... [code] ...
       series: [{
          name: 'MyPieChart',
          data: []
       ... [code] ...
   });

Thirdly, develop jQuery code for fetching data:

   $.ajax({
      type     : 'post',
      url      : '/path/to/php/data-script.php',
      dataType : 'json'
   }).done(function( jsonData ) {
      var objArray = [];
      $.each(jsonData, function(index,slice) {
         objArray.push({
            name: slice.name,
            y: eval(slice.y)
         });
      });
      graph.series[0].setData(objArray, true);
   });

It took me some time to figure out that I needed to (1) rearrange the data structure and (2) use eval() for parsing the value parameter y!

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

Switching views in AngularJS by using a controller to control the content displayed in the

My JavaScript web app utilizes AngularJS to simplify tasks, but I've encountered an issue. I'm trying to change views from an ng-controller using $location.path, but for some reason, the view isn't updating even though the path in the $loca ...

I encountered an error in my Rails 4 project where I got a NoMethodError stating "undefined method `id' for nil:NilClass" in my create.js

When I click a button, I'm attempting to display a partial. It seems like I am making an obvious mistake... and I suspect it's not related to the following code snippet: $('#modrequest').empty(); $('#modrequest').html("<%= ...

The concept of overloading operators in V8

Here's a question that I've been pondering, but couldn't seem to find any answers for on Google. While it may not be achievable in pure JavaScript, let's say I'm developing a container class in V8 and then returning that class bac ...

Tips on extracting specific information from a JSON object within an array using a key from a different object in Hugo

I am currently working with a data file in Hugo that contains information structured like the following: { "schedule": { "week1": [ { "day": 0, "away": 1, "home": 2, ...

The state of the checked value remains unaffected when using the Angular Material Checkbox

I am currently working on a list of elements and implementing a filter using pipes. The filter allows for multi-selection, so users can filter the list by more than one value at a time. To ensure that the filter persists even when the window is closed or t ...

Transforming pairs of names and values into objects by deserialization

I have a unique set of key-value pairs structured with the terms name and value similar to how a Key/Value object is defined, for example: [{"Name":"ActivityId","DataType":1,"Value":"a7868f8c-07ac-488d-a414-714527c2e76f"}, {"Name":"Address1","DataType": ...

When using JsonObj.getString(key), it is returning a zero instead of the intended value of 000

I have a simple JSON string: {"username":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="167b6f737b777f7a56667a776f78">[email protected]</a>","password":"0000"} When attempting to read the JSON string using the ...

Is your list rendering in Vue.js with AJAX ready to go?

At this moment, my Vue.js component is retrieving data from an Elasticsearch query and displaying it in a list like this: <li v-for="country in countries">{{ country.key }}</li> The issue I am facing is that I want to show users only a snippe ...

Conceal anchor links using jQuery by targeting their title attribute

Looking at the html below <li class="static"> <a title="blog" class="static menu-item" href="http://google.com">Blog</a> </li> <li class="static"> <a title="profile" class="static menu-item" href="http://profile.com"> ...

Issue with merging JSON in Angular using RxJS

Seeking assistance with combining two JSON objects in an Angular application. JSON Object 1: { "level1": { "level2": { "level31": "Text 1", "level32": "Text 2", "leve ...

Loop through an array of objects, then store each one in MongoDB

If I receive an Array of Objects from a Facebook endpoint, how can I save each Object into my MongoDB? What is the best way to iterate over the returned Array and then store it in my mongoDB? :) The code snippet below shows how I fetch data from the Face ...

Turn off the authentication middleware for a particular HTTP method on a specific endpoint

Currently, I am using Express/Node and have developed authentication middleware to validate JWT on each request. My requirement is to disable this middleware for a specific route (POST '/api/user/') while keeping it active for another route (GET ...

Enclose each instance of "Rs." with <span class="someClass">

I'm facing an issue with the currency symbol "Rs." appearing in multiple places on my website. I want to enclose every instance of this text within <span class="WebRupee">. However, if it's already wrapped in <span class="WebRupee">, ...

Validation of JSON array items

I am in need of a tool that can validate JSON data with specific examples. Here is the JSON fragment: { "optionsMinValue": 0 "optionsMaxValue": 56 "options": [ { "name": "name1&qu ...

Reset dropdown selection when a search query is made

Currently experimenting with Angular to develop a proof of concept. Utilizing a functional plunker where selecting an option from a dropdown populates a list of items from an $http.get( ). Additionally, there is a search input that should trigger its own $ ...

Extract information from a JSON string and present it on the screen

I am a complete novice when it comes to D3 (with very little experience in JS). Here are the lines of code I am working with: <script type='text/javascript'> data ='{"mpg":21,"cyl":6,"disp":160,"hp":110,"drat":3.9,"wt":2.62,"qsec":16. ...

Tips for rearranging objects within a jsPDF document to prevent vertical overlap when a table grows in size

I am new to React and Javascript. I have been struggling to find a solution to my issue while trying to create a .pdf document for a customer invoice using "jsPdf" along with its plugin "jspdf-autoTable". So far, everything is being generated correctly by ...

Alert: Prop type error encountered - The prop 'open' must be defined in Snackbar component

Recently, I've been implementing jest snapshot tests into my application. The main focus is on the LoginForm component. render() { return ( ... <DynamicSnack dialogOpen={this.props.dialogOpen} snackOpen={this.props.sna ...

Checking the validity of a JSON file extension using regular expressions

Using EXTJS, I have created a file upload component for uploading files from computer. I need to restrict the uploads to JSON files only and want to display an error for any other file types. Currently, I am able to capture the filename of the imported fil ...

Error Alert: React Native object cannot be used as a React child within JSON, leading to an Invariant Violation

When using React-Native: To start, here is the example code of a json file: Any placeholders marked with "..." are for string values that are not relevant to the question. [ { "id": "question1" "label": "..." "option": [ { "order": 1, "name": "..."}, ...