Is there a method for viewing or manipulating an object within a JSON file?

Could someone please assist me in accessing the total sum displayed in the chart using console.log? I have tried setting it using "var item": "[[value.sum]]", but it did not work. Any help is appreciated.

var chartData1 = [];

generateChartData();

function generateChartData() {
  var firstDate = new Date();
  firstDate.setDate(firstDate.getDate() - 500);
  firstDate.setHours(0, 0, 0, 0);

  for (var i = 0; i < 500; i++) {
    var newDate = new Date(firstDate);
    newDate.setDate(newDate.getDate() + i);

    var a1 = Math.round(Math.random() * (40 + i)) + 100 + i;
    var b1 = Math.round(Math.random() * (1000 + i)) + 500 + i * 2;


    chartData1.push({
      "date": newDate,
      "value": a1,
      "volume": b1
    });
  }
}

var chart = AmCharts.makeChart("chartdiv", {
  "type": "stock",
  "extendToFullPeriod": false,

  "dataSets": [{
      "fieldMappings": [{
        "fromField": "value",
        "toField": "value"
      }, {
        "fromField": "volume",
        "toField": "volume"
      }],
      "dataProvider": chartData1,
      "categoryField": "date"
    }
  ],

  "panels": [{
      "showCategoryAxis": false,
      "stockGraphs": [{
        "id": "g1",
        "valueField": "value",
        "comparable": true,
      }],

      "stockLegend": {
        "periodValueText": "Total: [[value.sum]]"
      }
    }
  ],

  "periodSelector": {
    "position": "left",
    "periods": []
  },

  "dataSetSelector": {
    "position": "left"
  }
});

chart.addListener('rendered', function(event) {
  var dataProvider = chart.dataSets[0].dataProvider;
  $(".amChartsPeriodSelector .amChartsInputField").datepicker({
    "dateFormat": "dd-mm-yy",
    "minDate": dataProvider[0].date,
    "maxDate": dataProvider[dataProvider.length - 1].date,
    "onClose": function() {
      $(".amChartsPeriodSelector .amChartsInputField").trigger('blur');
    }
  });
});
html, body {
  width: 100%;
  height: 100%;
  margin: 0px;
  font-family: Verdana;
}

#chartdiv {
width: 100%;
height: 100%;
}
<!-- jQuery stuff -->
<link rel="stylesheet" media="all" href="https://code.jquery.com/ui/1.12.0/themes/ui-lightness/jquery-ui.css" />
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js" integrity="sha256-eGE6blurk5sHj+rmkfsGYeKyZx3M4bG+ZlFyA7Kns7E=" crossorigin="anonymous"></script>

<!-- amCharts -->
<script src="https://www.amcharts.com/lib/3/amcharts.js"></script>
<script src="https://www.amcharts.com/lib/3/serial.js"></script>
<script src="https://www.amcharts.com/lib/3/amstock.js"></script>
<div id="chartdiv"></div>

Answer №1

const stockData = {
  "type": "stock",
  "extendToFullPeriod": false,

  "dataSets": [{
      "fieldMappings": [{
        "fromField": "value",
        "toField": "value"
      }, {
        "fromField": "volume",
        "toField": "volume"
      }],
      "dataProvider": chartData1,
      "categoryField": "date"
    }
  ],

  "panels": [{

      "showCategoryAxis": false,
      "stockGraphs": [{
        "id": "g1",

        "valueField": "value",
        "comparable": true,

      }],

      "stockLegend": {
        "periodValueText": "Total: [[value.sum]]"
      }
    }
  ],

  "periodSelector": {
    "position": "left",
    "periods": []
  },

  "dataSetSelector": {
    "position": "left"
  }
};

const chart = AmCharts.makeChart("chartdiv", stockData);

console.log(stockData.panels[0].stockLegend.periodValueText);
// Output: "Total: [[value.sum]]"

Answer №2

In order to access a specific field, you must first save the entire JSON data in a variable:

var data = {
  "type": "stock",
  "extendToFullPeriod": false,

  "dataSets": [{
      "fieldMappings": [{
        "fromField": "value",
        "toField": "value"
      }, {
        "fromField": "volume",
        "toField": "volume"
      }],
      "dataProvider": chartData1,
      "categoryField": "date"
    }
  ],

  "panels": [{

      "showCategoryAxis": false,
      "stockGraphs": [{
        "id": "g1",

        "valueField": "value",
        "comparable": true,

      }],

      "stockLegend": {
        "periodValueText": "Total: [[value.sum]]"
      }
    }
  ],

  "periodSelector": {
    "position": "left",
    "periods": []
  },

  "dataSetSelector": {
    "position": "left"
  }
};

var chart = AmCharts.makeChart("chartdiv", data);

console.log(data.panels[0].stockLegend.periodValueText);
// "Total: [[value.sum]]"

NOTE: [[value.sum]] in this code will not be interpreted, it will be treated as a literal string. The exact meaning of this syntax is unclear.

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

Shift div position when clicked and employ jQuery animations

I have been attempting to add animation to a DIV element by using jQuery. The goal is to move the DIV from the center to the left when it is clicked, but I am encountering some issues. The parent div has a position of "relative", and my initial idea was to ...

Trigger a JavaScript function upon clicking a link

Is it possible to have a CMS that loads articles using ajax, where the article is loaded through a function with parameters, and when a certain link is clicked, it redirects to the target page and launches the function on that page? For instance, let' ...

Utilize jQuery's addClass Method when Submitting a Form Using Ajax

When the form is submitted, I would like to add a class and display a loading animation before executing the AJAX request. However, when setting async to false in the AJAX call, the AJAX request will be executed first before displaying the loading animatio ...

Show SVG in its ViewBox dimensions

Currently, I am utilizing the img-Tag to showcase SVG images that have been uploaded by users onto my Amazon S3 storage. <img src="http://testbucket.s3.amazonaws.com/mysvg.svg" /> An issue arises once the image is displayed as it does not retain i ...

Using javascript to transform the entire list item into a clickable link

Currently, I am using PHP in WordPress CMS to populate slides on a slider. Each slide contains a link at the bottom, and my goal is to target each slide (li) so that when clicked anywhere inside it, the user is directed to the URL specified within that par ...

Guide on transforming observable<User> to Observable<boolean> in Angular 4

As a newcomer in Angular and Mean Stack, I need help implementing the canActivate() method to restrict admin routes. In my service file, the checkAdmin method returns an observable of type "User", but the canActivate method's return type is an observa ...

Issue encountered while trying to load electron-tabs module and unable to generate tabs within electron framework

I've recently set up the electron-modules package in order to incorporate tabs within my Electron project. Below are snippets from the package.json, main.js, and index.html files. package.json { "name": "Backoffice", "version": "1.0.0", "descr ...

An issue with importing chatgpt: ES Module require() not functioning as expected

I am facing an issue when trying to require the chatgpt package in my code. Despite having installed node fetch versions 2.6.6 and 2.7.1, the package is still throwing errors. Additionally, I have updated my package.json file with "type": "m ...

Utilizing cross-domain AJAX for JSON requests

I'm currently on the website site.com attempting to retrieve some JSON data from my node.js server running on port 8080. Encountered this particular error message: XMLHttpRequest cannot load http://site.com:8080/json/1. Origin http://site.com is not ...

Navigating the strict same-origin policy by utilizing a PHP proxy script for jQuery/JSON API connections

I've been working on a jQuery script that needs to fetch data from a JSON file located on a server that I can't directly access. To handle this, I created two scripts - a PHP proxy script: <?php $content = file_get_contents($_GET['http ...

I seem to be stuck trying to figure out what's going wrong when receiving JSON data

I have spent hours researching on Stack Exchange and Google to gather different information. Here is what I have in guess.php: PHP header('Content-type: application/json'); get_rating($cleanMovie); json_encode(array($id)); The get_rating funct ...

What is the most straightforward method to convert a current Express node app into a static site?

After primarily working with React and create-react-app, I've grown accustomed to the convenience of having a build utility for npm that simplifies deploying projects to static web hosting platforms like github pages or surge. This process ultimately ...

Fixing a broken field in Kibana through analysis

I am utilizing an ELK stack to ingest structured JSON logs from filebeat, with examples like these: {"what": "Connected to proxy service", "who": "proxy.service", "when": "03.02.2016 13:29:51", "severity": "DEBUG", "more": {"host": "127.0.0.1", "port": 20 ...

Adding elements into a PHP MySQL associative array using the array_push function

Trying to construct an associative array with PHP, utilizing an ajax script that accesses a JSON file. The script was successfully tested with the following PHP code: $testLocs = array( 'loc5' => array( 'info' => 'Some rand ...

Generate HTML table with CSS dynamically applied through jQuery

After performing some calculations and applying CSS rules using the .css() function in jQuery to color the background of a table, I am facing an issue when trying to print the page. The printed page appears in black and white without retaining any styling ...

Upon a successful AJAX post request, the page fails to display

I'm encountering an issue connecting my front-end JavaScript to my back-end Node/Express. Although the requests from my client-side js to the server return successful, the page I am requesting fails to render. On the server side, here is my code: ap ...

Database connection error: Authentication protocol requested by server not supported

I have been struggling with the issue outlined in this link: MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client Even though I have tried following the recommendations, I am still encountering e ...

Managing configuration variables in ExpressJS for various environments

Is it possible to set a variable for different environments when defining the environment? app.configure 'development', () -> app.use express.errorHandler({dumpExceptions: true, showStack: true}) mongoose.connect 'mongodb://xxx:<a h ...

Choose a specific 24-hour range with the Date Interval Selector

I am currently utilizing the Date Range Picker plugin for bootstrap from the website http://www.daterangepicker.com/#examples, and I have a requirement to set the maximum date time range to be within 24 hours. Below is an example demonstrating how I can s ...

Conditionally displaying an input model in Vue.js using v-if

Just starting to learn vue.js and I'm looking to display table data. My idea is that when the table is in display mode, it should only show the data. However, when I click on the edit button of a table row, I want that specific row to switch to edit m ...