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

Is it possible to rearrange the order of items in a JSON sequence?

Is it possible to rearrange the order of json items? For instance: [ { "category": "Science: Mathematics", "type": "multiple", "difficulty": "medium", "question": "In a complete graph G, which has 12 vertices, how many ed ...

Is jQuery failing to serialize the form data?

I have a question regarding my form. When I try to serialize it using a jQuery script, the output is empty. Could someone please assist me with this issue? Here is a snippet of my form: <form id="tabb2"> <!-- *************************** ...

Using jQuery to loop through a collection

I have a page that displays a list of posts. When a user clicks on the show comments button for a particular post, the comments associated with that post become visible. This functionality is achieved by using this and then searching based on the click loc ...

What are some ways to utilize an empty array that has been declared in React's initial state?

I am currently in the process of developing an application that displays a collection of various lists. However, I have encountered a roadblock when attempting to access an empty array that I initialized when setting up the initial state. Here is the state ...

A guide to accessing and managing events for the child inside a div element using extjs4

How can I dynamically switch between the divs with classes "icon-right" and "icon-left" when clicked? Here is an example of the HTML and ExtJS code involved: Html code: <div class="msg"> <div> <div cla ...

How to pinpoint a particular element in a parsed json using Ruby

I have a JSON string that I need to parse using Ruby. The string looks like this : [ { "id": 1, "player_id": "not_this_one\n", "highscore": 23 }, { "id": 2, "player_id&qu ...

Guide on displaying content in two different tabbable ID's when one tab is selected in a Rails 3.2 App using Twitter Bootstrap's Tabbable Tabs

My implementation using Twitter Bootstrap's bootstrap-tab.js includes: <ul class="tabnavcenter" id="myTab"> <li class="active"><a href="#home" data-toggle="tab">about</a></li> <li><a href="#tab2" data-togg ...

The CKEditor is having trouble properly opening code snippets

I have been using ckeditor 4.4 along with the code snippet plugin. Initially, when I create a document with a rich code snippet and save it, everything works perfectly fine. The source code for what is generated looks like this: <pre><code>&am ...

The drop-down list was designed with a main button to activate it, but for some reason it is not functioning properly. Despite numerous attempts, the list simply will not display as intended

<html> <body> <button onclick="toggle()" class="nm" > main</button> <div class="cntnr" style="display : none;"> <ul class="cnkid"> <li class="cnkid"><a class="cnkid" ...

Unlocking the Power of ReactJS: Passing Values in Material UI for Advanced JSON Structures

How can I access complex objects in the GRID component of material UI? Specifically, I am trying to access the ami_info.account, but it only displays Undefined in the UI. var columns = [ { field: 'id', headerName: 'ID', width: 90, ...

Can an older style class be inherited from an ECMAScript 6 class in JavaScript?

When I run the code below on Node.js version 4.2.1: 'use strict'; var util = require('util'); class MyClass { constructor(name) { this.name = name; } } function MyDerived() { MyClass.call(this, 'MyDerived'); } ...

Utilizing AJAX to dynamically load file references and embed iframes

Is the use of multiple iframes on a website impacting its loading speed? Also, regarding AJAX, let's say I have two JSP pages. The first one contains an AJAX call to the second JSP page. Both pages have JavaScript functions with the same name, let&apo ...

I'm sorry, but we were unable to locate the /bin/sh

After running a command using execSync that runs with sh, I observed the following: spawnSync /bin/sh ENOENT bin is now included in the PATH environment variable. Any ideas on this issue? ...

Parsing of the module failed due to an unexpected character appearing when trying to insert a TTF file into the stylesheet

As a newcomer to Angular, I recently completed the tutorial and am now working on my first app. While trying to add an OTF file, everything went smoothly. However, when I made a change to my app.component.css file and included this code snippet: @font-fa ...

Exploring JSON data for auto-complete suggestions

Upon receiving the object from the source, it looks like this - ["road",[["road",53,"0E"],["roadtrip",53,"1E"],["roadrunner",53,"2E"],["roadster",53,"3E"],["roadside",53,"4E"],["roadrage",53,"5E"],["roadcycling",53,"6E"],["roadsideamerica",53,"7E"]],{"k": ...

AngularJS can easily interpret and extract information from HTML code

As an example, I have dynamically generated HTML on my webpage like this: <ul> <li>Country</li> <li>State</li> <li>City</li> </ul> I am looking to send this information to the database after clicking a b ...

Ways to include text with specific choices in a drop-down menu?

Within a form, I am encountering a situation where a select box's options are pre-selected through ajax based on a previously entered value. I am now seeking a way to append additional text to these pre-selected options only. for (i in data) { $("#my ...

Retrieve various data points from JSON with the implementation of JSON query in Ansible

I have the following output code snippet: ok: [localhost] => { "output": { "ansible_facts": { "openstack_servers": [ { "az": "xxx", "cloud": "xxx", "cre ...

Guide on programmatically choosing an option within a variable with the help of jQuery

Imagine having a variable named html, which holds select options like this: var html = '<select>'+ '<option value="10">10</option>'+ '<option value="20">20</option>'+ ...

Using jQuery to store the selection made in a select element option

Hello everyone, I need some help with saving the selected option on my form by the user. I am not sure how to accomplish this. Let me give you a brief overview of my setup... On my home page, I have a form that looks like this: <form class="form-home ...