What is the process for converting a JSON File into an array using javascript?

Hey there, I'm new to programming so please bear with me XD. I've been struggling for 2 days trying to figure this out with no luck.

So here's the deal - I have a chart in JavaScript that is pulling data from a file called test.json, which is located in the same directory as the chart file:

data2020 = '[0,0,0,0,0,202,50857,116823,113280,109400,99846,83975]';
data2021 = '[58578,15864]';

I recently learned how to update the data and realized that my JSON format was not standard when using this script:

file_put_contents('test.json', $newJsonString);

The updated JSON format now looks like this:

[{"data2020":[0,0,0,0,0,202,50857,116823,113280,109400,99846,83975],"data2021":[58578,15864]}]

But now my chart can't read this new JSON file. After some investigation, I suspect the issue may be with my chart setup since I only have this simple configuration:

  data: {
    labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
    datasets: [{
      label: "Produksi 2020 : ",
      lineTension: 0.3,
      backgroundColor: "rgba(78, 115, 223, 0.05)",
      borderColor: "rgba(235, 180, 39, 1)"
      // more dataset configurations...
      data: JSON.parse(data2020),
    },

Someone suggested adding both scripts to my PHP file as follows:

<script src="../js/test.json"></script>
<script src="../js/chart.js"></script>

Basically, all I did was use JSON.parse and nothing else. I understand that I need to convert my JSON file into an array and use that array in the data. But I'm stuck on figuring out how to do that. So, the question is pretty straightforward - how do I convert a JSON file to an array in JavaScript?

I tried reading through this link for help, but it's still a bit confusing for me XD: How to read an external local JSON file in JavaScript?

Answer №1

Typically, JSON files start and end with { and }, which allows JSON.parse() to successfully parse the file. To illustrate this, simply make the following adjustment:

[{"data2020":[0,0,0,0,0,202,50857,116823,113280,109400,99846,83975],"data2021":[58578,15864]}]

becomes

{[{"data2020":[0,0,0,0,0,202,50857,116823,113280,109400,99846,83975],"data2021":[58578,15864]}]}

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 display a success notification when a transaction is successfully executed in web SQL

var brand = "Glare"; var price = "3000$"; var color = "blue"; var success = tx.executeSql("INSERT INTO truck (brand, price, color) VALUES ('"+brand+"','"+price+"','"+color+"' ")"); if(success) { alert("successfully insert ...

Is the MVC pattern adhered to by ExpressJS?

Currently, I am diving into the world of creating an MVC Website With ExpressJS using resources from I'm curious to know if ExpressJS strictly adheres to the MVC pattern, or if it follows a different approach like Flask which focuses more on the "C" ...

What could be the reason behind the child component updating without triggering a re-render in Reactjs?

I am encountering an issue with my main component and child chart component. Even though the main component updates the state of the child chart component upon connecting to a websocket, the chart does not redraw as expected. Interestingly, when I click on ...

Pass information from ColdFusion to jQuery

I'm attempting to achieve a similar result as this, but I believe the syntax is not quite right: <cfset details = '{ name: "name", address:"address"}' /> <img data-details='#details#' onClick="DisplayDetails()" /> &l ...

What is the best way to convert a circular JSON object to a string

Is there a way to stringify a complex JSON object without encountering the "Converting circular structure to JSON" error? I also need its parser. I am facing issues every time I try to use JSON.stringify and encounter the "Converting circular structure to ...

Prevent the query from being executed by halting the AJAX call

Within my web application, I have a specific button that triggers an AJAX call upon being clicked. On the server side, I need to run a query against a database. I am concerned about the execution time of these queries and worry that users may be impatient ...

Utilizing JSON for HTML conversion in Codeigniter

public function getCrew(){ $search = $this->input->post('name'); if($this->input->post('ajax') && (!empty($search))){ $result = $this->model->getNames($search); foreach($result as $r){ ...

Explanation on retrieving JSON data from a ListView and passing it to another activity using SQLite in Android Studio

My goal is to navigate from the HOMESCREEN to a new activity, INTERNETSEARCHSCREEN, and then finally to the EDITINGSCREEN. I have successfully displayed JSON data on a listview but now I want to select a movie from the listview and display specific fields ...

What is the best way to verify the presence of a value in an SQL column?

I need to check if a value exists in a column. If the value already exists, I do not want to insert it into the table. However, if it does not exist, then I want to add new data. Unfortunately, my attempted solution hasn't been successful. You can fi ...

Conditional Matching with Javascript Regular Expressions

My strings are formatted like this: #WTK-56491650H #=> want to capture '56491650H' #M123456 #=> want to capture 'M123456' I am trying to extract everything after the # character, unless there is a dash. In that case, I onl ...

Steps for rearranging the order of CSS grid layout

Could you assist me in implementing a grid layout that fulfills these specific criteria? I'm unsure of how to proceed, so any guidance would be greatly appreciated. When there are more than 9 items, the current layout changes the order from top to bo ...

perform an action in PHP when a button is clicked

I'm currently developing a PHP admin panel that displays a list of users in an HTML table format. Each row in the table includes a button that allows the admin to send a notification to the selected user. Below is the code I used to create and displa ...

Strategies for handling user typos in a JavaScript prompt

Hi there! Just wanted to say that I'm new to this website, so please forgive any posting mistakes I might make. I'm currently taking a web technology class where we're learning JavaScript. In a previous lesson, we covered HTML5 and CSS. Our ...

Developing a password strength checker using Javascript for ultimate security

Currently encountering an issue with my javascript project. The main goal is to validate user input against a list of known bad passwords and also their "1337" versions. Initially, checking for the basic bad password list was straightforward. However, th ...

Using AJAX to add an event listener and passing parameters to a separate function

Short and sweet - I've got a loop that creates a series of dynamic buttons, and when one of them is clicked, I need to pass its id attribute to another file to generate a new page on the fly. Here's the code snippet: for (var i in data.contacts ...

Making AngularJS work with angular-ui bootstrap and ensuring compatibility with IE8

Having trouble getting AngularJS code that utilizes angular-ui bootstrap to function properly in IE 8? Following the guidelines in the AngularJS developer guide on IE didn't seem to solve the issue for me. I inserted the code snippet below into my ind ...

Add the file to the current directory

As a newer Angular developer, I am embarking on the task of creating a web page that enables users to upload files, with the intention of storing them in a specific folder within the working directory. The current location of the upload page component is ...

Issue with passing parameter values in MVC Html.ActionLink

Currently, I am experimenting with MVC for a demonstration and have managed to put together some components. However, I am encountering difficulties with an Html.ActionLink. The goal is to display a series of dropdown lists to the user that must be selecte ...

StyledTab element unable to receive To or component attributes

Is there a way to use tabs as links within a styled tab component? I've tried using the Tab component syntax with links, but it doesn't seem to work in this scenario: <Tab value="..." component={Link} to="/"> If I have ...

Leverage the power of AJAX and PHP to securely save comments for future

I have coded a JavaScript function that uses POST and GET methods to send comments from an input field and retrieve them when the page reloads. However, I am unsure of how to handle the data after it is sent in order to save it and access it again later. E ...