How to process JSON data that includes a function

I'm trying to replicate a similar diagram using dynamic input data. Here is a basic example of how I'm attempting to achieve this:

<script>

var myYears = ', 1991, 1992, 1993, 1994, 1995, 1998';  //auto-generated 
var myValues = ', 1, -3, -6, -5, 2, -3'; //auto-generated 

var textJSON = '{' +
        '"data": {' +
            '"x": "year",'  +
            '"columns": ['  +
            '   ["year"' + myYears +'],' +
            '   ["value"' + myValues +']' +
            '       ],' +
            '"type": "bar"' +
            '}' +
            '}' ;

var c3JSON = JSON.parse(textJSON);
var chart = c3.generate( c3JSON );   

</script>

Everything works fine until I try to incorporate the color function into my text. It seems that parsing it to JSON format doesn't work as expected.

Has anyone encountered a similar issue or knows how to correctly include the color function in the JSON object?

Answer №1

Avoid manually converting your values to a JSON string using concatenation and then parsing it back to a JS object. It's not the best approach.

Instead, try this method:

var myYears = ', 1991, 1992, 1993, 1994, 1995, 1998';  //will be created automatically
var myValues = ', 1, -3, -6, -5, 2, -3'; //will be created automatically

var yearsArray = myYears.split(', '); 
yearsArray[0] = 'year';

var valuesArray = myValues.split(', '); 
valuesArray[0] = 'value';

String.prototype.split function will transform your string

, 1991, 1992, 1993, 1994, 1995, 1998

into an array by splitting it at ", ". This will result in the following array:

["", "1991", "1992", "1993", "1994", "1995", "1998"]

To specify a name for your column as the first item, simply assign it to yearsArray[0]. The same logic applies to the values array.

Now you can use this code snippet:

var myYears = ', 1991, 1992, 1993, 1994, 1995, 1998';  //will be created automatically
var myValues = ', 1, -3, -6, -5, 2, -3'; //will be created automatically

var yearsArray = myYears.split(', '); 
yearsArray[0] = 'year';
var valuesArray = myValues.split(', '); 
valuesArray[0] = 'value';

var chart = c3.generate({
        data : {
            x : 'year',
            columns : [
                yearsArray,
                valuesArray
            ],
            type : 'bar',
            labels : true,
            color : function (color, d) {
                if (d.value < -1) {
                    return d3.rgb('red');
                } else if (d.value >= -1 && d.value <= +1) {
                    return d3.rgb('grey');
                } else {
                    return d3.rgb('blue');
                }
            }
        }
    });

Consider refining the format of dynamically generated strings to enhance clarity and transparency.

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 is the best way to pass parameters to a PHP script using AJAX to ensure they are properly processed on the server side?

I'm working with the following function: function myFunction () { $.getJSON('remote.php', function(json) { var messages = json; function check() { ... In this function, I call the remote.php script which e ...

What is the best way to reload scripts each time a component is mounted?

My jQuery scripts include animation effects that need to be refreshed whenever something new is rendered on the page. However, I am facing an issue where the jQuery scripts are not being refreshed as needed. Below is my router configuration: export defau ...

Difficulty activating JavaScript function - unsure of proper implementation

I'm having trouble with calling a function instead of an alert in my code. I tried using FunctionsName(); and removing the alert(''); but it doesn't seem to be working for me :( Could someone please take a look at the following code an ...

Creating structured paths for retrieving data via HTTP GET requests

In my Laravel project, I have routes set up for requests in a traditional way: Route::get('edit/{user}', 'AdminUserController@getUser'); Route::post('delete', 'AdminUserController@deleteUser'); However, I am facing ...

Storing information using ajax and JSON through Handsontable to send to a Web API

I am encountering an issue when sending my Handsontable data via ajax to a Web API POST method. The data appears as blank on the web api end despite showing up correctly in Fiddler. It seems like the data is not being deserialized. Below is my code snippet ...

When incorporating reduce into your code, remember to expect an undefined

Imagine you have an array like this: const novels = [ { id: 1, name: 'The Da Vinci Code', genre: 'Mystery', author: { name: 'Dan Brown', birthYear: 1964, }, releaseYear: 2003, }, { ...

The export of 'alpha' is not available in the '@mui/system' module

Help! I am encountering an error related to the @mui/material library. I have already looked into the package.json file of mui/system and it seems that 'alpha' is exported in it. ./node_modules/@mui/material/styles/index.js Attempted import erro ...

Retrieve the Nth class of an element that has multiple classes without relying on the .attr("class") method in jQuery

Within a container with two styles, the initial nested div <div class="datacheck"> <div class="classic_div_data customdataid_305"> some values are included here </div> <div class="optiondiv"> </div> </div& ...

Having trouble with implementing ng-hide and ng-show functionality

I have been working on creating my very first Angular website and so far, everything has been going smoothly with the first page. However, I am facing an issue with the second page not appearing as expected when it meets the condition set with ng-show in t ...

Implementing basic authentication in Socket.IO on a Node.js server

Currently, I am attempting to develop a basic websocket client for establishing a connection with a device. However, the device requires both a username and password for authentication purposes, posing a challenge for me as I struggle to figure out how to ...

Troubleshooting: Magento checkout page keeps scrolling to the top

We are experiencing an issue where, during the one page checkout process, the next step is not automatically scrolling to the top of the page when it loads. After a user fills out all their billing information and clicks continue, the next step appears ha ...

Determining if a map array value is being duplicated with a distinct key in JavaScript

I am facing an issue with a Map that has "String" as keys and "Array" as values. My problem is figuring out how to check if an array item is present in a different "Array" value, specifically in the "Array" of a different key within the map. For example: ...

Using jQuery to target adjacent elements excluding those that are separated by other text

I have been attempting to locate and combine adjacent em tags within paragraphs, but it has proven to be a more challenging task than I initially anticipated. Let's explore some examples to illustrate this issue: <p><em>Hello</em>&l ...

Is there a way for me to extract all the elements within an object nested inside an array and then append them to another array?

I'm currently facing a challenge that's bothering me quite a bit. My skills in handling JSON data manipulation are not up to par. The problem I'm dealing with involves an array of multiple objects, each containing some data. Within these ob ...

Using JQUERY for navigating through pages in a REST API while utilizing deferred functionality

I am utilizing a REST API in jSON format to fetch records. My Approach The REST API retrieves records in jSON format. Initially, I retrieve the top 6 records, along with an additional jSON node containing a forward paging URL. This URL is assigned t ...

AJAX request stops functioning once the page is reloaded

As a beginner in JavaScript, I am facing an issue with my AJAX call. I have set up the call to process a back-end function when a button is clicked and expect to receive a response once the function is completed. However, whenever I refresh the page whil ...

Is JavaScript responsible for creating threads for non-blocking AJAX requests?

It is widely believed that JavaScript operates on a single-threaded model, but it has the ability to run asynchronously. One intriguing aspect is how this single-threaded model manages non-blocking AJAX requests. Consider a scenario where a non-blocking A ...

The use of jQuery for fetching posts via ajax can lead to a crash in the browser

I have a social media platform where I implemented jQuery on the main feed page. The jQuery is set up so that as users scroll down, the next batch of posts is fetched using ajax and added to the DOM. However, after a few ajax requests, the browser slows do ...

Changing the Class of an Element in a Different Component with Angular 2+

Currently in a project utilizing Angular 4, I have implemented two components: app.component and other.component Within app.component.html, there exists a div with the name attribute myClass. <div class="myClass"></div> In the other.componen ...

Incorporate the previous page's location path into the next page using Props in Gatsby Link

My website has multiple pages with paginated lists of blog posts, each post generated from markdown using createPage(). Each page in the /posts directory displays 3 post previews and subsequent pages are numbered (e.g. /posts/2). I am trying to pass the p ...