Unforeseen alterations in value occur in JavaScript when converting to JSON format

Having trouble generating a gantt chart from a JSON string, specifically with parsing the JSON string into a JSON object.

I have a variable myString containing a JSON string that looks like this:

{"c": [{"v": "496"}, {"v": "Task name 1"}, {"v": "9, "}, {"v": "Date(2018,6, 19)"}, {"v": "Date(2018, 6, 21)"}, {"v": null}, {"v": 100}, {"v": null}]}

When I use

var jsonData = JSON.parse(myString);
, the values "Date(2018,6, 19)" and "Date(2018, 6, 21)" get changed to "Date(2018,7, 19)" and "Date(2018, 7, 21)".

I am unsure what is wrong with my code. Here is the full code snippet:

 $.ajax({
                        type: "GET",
                        url: URL,
                        data: data,
                        contentType: "application/json; charset=utf-8",
                        success: function (response) {
                            console.log(response['chart_data']);

                            var jsonData = JSON.parse(response['chart_data']);
                            console.log(jsonData);
                            var chart_height=jsonData["rows"].length;
                            google.charts.load('current', {'packages': ['gantt']});
                            google.charts.setOnLoadCallback(drawChart);

                            function drawChart() {

                                var data = new google.visualization.DataTable(jsonData);

                                var options = {
                                    width: document.getElementById("task_list").offsetWidth,
                                    height:30*chart_height,
                                    gantt: {
                                        trackHeight: 30
                                    }
                                };

                                var chart = new google.visualization.Gantt(document.getElementById('chart_div'));
                                chart.draw(data, options);
                            }
                        }
                    });

SOLUTION:

Thanks to user1531038, it was noted that the new Date() function was triggering during parsing, and the Date function counts months from 0 to 11.

Answer №1

Everything is running smoothly as planned because both Date(2018,6, 19) and Date(2018, 6, 21) are being recognized as strings :

https://i.stack.imgur.com/IVRpl.png

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

JOLT Evolution: Modify field value depending on the nested element value

I am struggling with transforming a JSON structure to meet specific requirements before sending it to an external API. Our team is utilizing JOLT for these transformations, but I have hit a roadblock in achieving the desired output. The challenge lies in d ...

Decoding Contentful Webhooks with unique JSON formats

Currently, I am utilizing the Contentful-webhook-server to monitor webhooks for unpublished content. server.listen(30000, function(){ console.log('Contentful webhook server running on port ' + 30000) }); server.on('ContentManagement. ...

Angular2 - Utilizing Promises within a conditional block

I'm currently facing an issue where I need to await a response from my server in order to determine if an email is already taken or not. However, I am struggling to achieve this synchronously. TypeScript is indicating that the function isCorrectEmail( ...

When you input text into a contenteditable div, it automatically gets placed inside a span element instead of being placed

I'm having an issue with my contenteditable div. Whenever I click the button, a span is inserted into the div. However, when I start typing, the text goes inside the span instead of outside it: jQuery(document).ready(function($) { let input = $(" ...

Node JS Client.query not returning expected results

Currently, I am developing a Web Application that interacts with my PostgreSQL database. However, when I navigate to the main page, it should display the first element from the 'actor' table, but unfortunately, nothing is being retrieved. Below i ...

Easily integrate a "Purchase" button into your Chatfuel chatbot with the JSON API block and Stripe payment system on Facebook Messenger

I'm currently facing a roadblock while attempting to create a Facebook Messenger bot through the Chatfuel platform. Specifically, I am struggling to figure out how to display the "Buy" button via the JSON API block. My goal is to utilize the Stripe ve ...

Mastering file handling with jQuery File Upload Middleware in Node.js Express: blending files and branding with watermarks

I was successful in setting up the jquery-file-upload-middleware with express.js 4.0, but I am struggling with configuring it properly. Here is the script I used for upload: var upload = require('jquery-file-upload-middleware'); upload.configur ...

`Python handling inheritance within complex objects loaded from JSON files`

In my project, I've implemented a dictionary that holds string keys and instances of different classes as values. Now, my goal is to serialize this data using JSON and then deserialize it back to its original objects. class A: def __init__(self, ...

Using a timer to make Ajax calls twice on a single webpage

Can multiple ajax calls be made simultaneously on the same page to different receiving div tags? I am struggling to find a solution to this issue. I have a total of 3 pages: a home page, and two PHP pages named status and alert which echo the results. Wi ...

What is the best approach to have a React page render only the specific component that has changed, rather than re

Recently, I've been facing an issue with a toggle implementation where the page always re-renders the entire content upon the first click of the toggle. Here is a snippet of how it looks: export default function Toggle({isChecked, label}: Props) { r ...

PHP code to generate a JSON file with a multi-dimensional array: "

Within my web application, I am utilizing JSON. It is necessary for me to generate the following JSON file format using PHP. { "title": "A fantastic article", "clicks": 4000, "children": null, "published": true, "comments": [ ...

Issue with Pagination functionality when using Material-UI component is causing unexpected behavior

My database retrieves data based on the page number and rows per page criteria: const { data: { customerData: recent = null } = {} } = useQuery< .... //removed to de-clutter >(CD_QUERY, { variables: { input: { page: page, perPag ...

Tips for controlling the size of a canvas element: setting minimum and maximum width and height properties

function convertImageResolution(img) { var canvas = document.createElement("canvas"); if (img.width * img.height < 921600) { // Less than 480p canvas.width = 1920; canvas.height = 1080; } else if (img.width * img.he ...

The system has removed all content within the fields

I have created a code to generate a dynamic table. The problem I am facing is that when there are multiple rows in the table, clicking on the delete button deletes all field values instead of just deleting the data for the specific row where the delete b ...

Purge excess bins that are not in use

I need to delete a large number of inactive bins from the system, but I can't find an option for mass deletion or inline editing using saved searches. Is there another method to accomplish this task since I have hundreds of records to delete? ...

Seeking assistance with changing the pages

Looking for assistance with troubleshooting my function. All variables are accounted for. var swith = document.getElementById("sub"); var one = document.getElementById("rule"); var two = document.getElementById("cool"); var three = document.getElementByI ...

After two HTML injections, Javascript ceases to function properly

I am in the process of developing a chat feature for my website. The layout includes a conversation section on the left and a list of users on the right. When a user's div is clicked, their ID is transmitted to the Django back end. Subsequently, full ...

What is the most effective way to transmit multiple pieces of server-side data to JavaScript?

Imagine having multiple Javascript codes embedded in pages. Currently, it's simple to initialize variables by using Print/Echo statements to set JavaScript values. For example: var x = <?php echo('This is a value');?> Initially, I co ...

JSON: Automatically choose the radio button based on the provided response

Is there a way to automatically select the checked state of radio buttons based on data retrieved from a database? I need to populate this form's radio button with data <div class="col-md-4"> <label> <input type="radio" name="m ...

Using PHP to encode an emoji as a plain text Unicode string

I am currently working on a website and Unity project that communicate with each other via a web server using web sockets. I have successfully managed to encode/decode messages using JSON and implemented emojis in Unity for display purposes. However, when ...