Transform JSON data into an array of arrays

For my project, I am using the python SimpleHTTPWebserver to serve up various files, including a valid JSON file named "file.json". In my javascript front end, I need to interpret this JSON object as an array of arrays. For example:

{
  "val1": 101,
  "val2": 202
}

Should be transformed into

var jsonFile = [['val1', 101], ['val2', 202]]

Unfortunately, I am unable to even load the file's raw content into a variable. I am new to javascript and have attempted the following:

<html>
<head>
    <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
    <script src="http://d3js.org/topojson.v1.min.js"></script>
    <script src="http://d3js.org/d3.geo.projection.v0.min.js" charset="utf-8"></script>
</head>
<body></body>
<script type="text/javascript">
  var mydata = JSON.parse("file.json");
</script>
</html>

However, this code snippet is throwing an error:

VM89:1 Uncaught SyntaxError: Unexpected token s in JSON at position 0 at JSON.parse () at :1:6

Being new to javascript, I want to keep things simple using either plain javascript or a library like jQuery. I just can't figure out why this code isn't working. Can someone please help me with this issue?

Answer №1

To access the json data, you must first request the files from the server.

By making an ajax request and specifying json, you can avoid the need to parse the data.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>

<head>
  <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
  <script src="http://d3js.org/topojson.v1.min.js"></script>
  <script src="http://d3js.org/d3.geo.projection.v0.min.js" charset="utf-8"></script>
</head>

<body>
<script type="text/javascript">
  $.ajax({
    url: "path/to/json/file",
    type: 'GET',
    dataType: 'json',
    success: response => {
      console.log(Object.entries(response));
    }
  })
</script>
</body>

</html>

Utilizing Object.entries() allows you to transform an object {key:value} to [[key,value]]

let x = {val1: 101,val2: 202};
console.log(Object.entries(x))

Answer №2

JSON.parse function can parse a JSON object string such as "{"foo":"bar"}" and convert it into a JSON object. If you are passing a file name instead of the content, it will result in an error due to the incorrect format. To properly parse the JSON file, you need to fetch its content and then pass it to JSON.parse. If you have included jQuery in your project, you can retrieve the file using XMLHttpRequest to make an asynchronous request (also known as AJAX).

$.ajax('/url/of/your/file.json', {
    success: function(content) {
        var json = JSON.parse(content);
        var resultArray = Object.keys(json)
                                .map(function(key) {
                                    return [key,json[key]];
                                })
                                .reduce(function(container,nextArray) {
                                    container.push(nextArray);
                                    return container;
                                }, []);
       console.log(resultArray); // This is the desired resultArray
    }
});

Learn more about $.ajax()

Visit the documentation for JSON.parse()

Understand Object.keys()

Explore Array.map()

Learn about Array.reduce()

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

Encountering an error with code 'MODULE_NOT_FOUND' while attempting to deploy a bot on Heroku

Can anyone assist me with deploying my Twitter Bot on Heroku? I've configured the Twitter keys in the Heroku Vars, ensured the package.json is correct, and searched on Google for a solution, but I'm still facing issues. I'm not sure where I& ...

Having trouble retrieving the value of a textarea within a jQuery UI dialog box

I attempted to place a textarea within a dialog box, with the intention of retrieving the value of that textarea when the "ok" button is clicked. However, I am encountering difficulties in retrieving the value. What could possibly be causing this issue? ...

A guide to using Python to execute transformations on JSON data

While I have experience running data transformation using Python on CSV file formats, working with JSON formats is new to me. I am currently dealing with streaming JSON data and looking to apply an MD5 algorithm to generate a hash. I have already created ...

How can we solve the issue of missing props validation for the Component and pageProps in _app.js?

Below is the code snippet from _app.js for a nextjs project that uses typescript import React from 'react' import '../styles/globals.css' function MyApp({ Component, pageProps }) { return <Component {...pageProps} /> } export ...

Creating JavaScript objects through function calls

let getBoxWidth = function() { this.width=2; }; alert(getBoxWidth.width); Hello there! Can you explain why the output is undefined in this scenario? ...

Can config values be dynamically set from an Excel file in Protractor?

I am currently working on parameterizing capabilities using an Excel sheet. For this task, I am utilizing the npm exceljs package for both reading and writing data. Below is a snippet of the code that demonstrates how I am trying to achieve this: //This f ...

An effective way to determine the size of a browser through javascript

In an effort to enhance the responsiveness of a website, I have included the following code snippet on one of my pages: document.write(screen.width+'x'+screen.height); However, I am encountering an issue where the code displays my screen resolu ...

Retrieve image details and display them in the console when the page is resized

Query: How can I retrieve and monitor the src, width, and height of all images on a webpage and display this information in the console whenever the page's size changes? Sample Code Snippet: var images = document.getElementsByTagName('img' ...

Ways to determine the height of a row within a flexbox

Is it possible to obtain the height of each row within a flexbox container using JavaScript? For instance, if there are 3 rows in the container, can I retrieve the height of the second row specifically? ...

What could be causing this issue with the ng-bind and ng-show directives not functioning as expected?

Attempting to show data retrieved from Google's Place Service. Oddly enough, the object can be logged to the console within the controller, but the directives in the HTML file remain blank. Since no map is being used, a div element was passed as the n ...

When I try to use this code in Eclipse, it runs without any issues. However, when I attempt to convert it into a

In my code snippet, I am reading a JSON array in Java to display the h1 value. It works perfectly in regular Java environment, but when I use it in Maven, I encounter a compile time error. [ERROR] \WebApp_maven\SimpleCar1\src\main&bsol ...

Using a computed property setter in Vue.js/Javascript while focusing on a datepicker can lead to crashing the browser

Can anyone explain why my javascript / vuejs code is crashing on my JSFiddle when I focus on the start date datepicker (causing the browser to hang)? If you uncomment the endDate computed property and comment out the current one, it works fine but the fun ...

Ways to retrieve a variable within the init() function

My current project involves using datatables along with ajax to display information dynamically. Below is the code snippet I am working with: // Setting up the module var DatatableAdvanced = function() { // Examples of Basic Datatables var _c ...

The app constantly requests permission for geolocation services

While experimenting with the geolocation API, I encountered an issue where my page kept repeatedly asking for permission upon refresh. To work around this problem, I attempted to save my coordinate data to local storage but encountered difficulties in ma ...

Returning to the initial state after clicking on an element within a repeated set in AngularJS?

I'm currently facing a challenge, mainly due to my lack of understanding in basic AngularJs concepts. The issue arises when I interact with a list of clickable words. When I click on any of these words, their color changes individually thanks to the i ...

Passing the selected value from a drop-down list to a controller based on another one using Ajax and JSON in ASP.NET MVC

One of the challenges I faced was setting up a drop-down list that depended on another drop-down. To achieve this, I utilized an Ajax call in JSON format to retrieve the necessary data for the dependent drop-down list. However, I encountered an issue wher ...

The combination of NextJS and Firebase Auth using the GoogleAuthProvider is powerful

I am encountering challenges while trying to integrate firebase authentication with Google Provider in NextJS. I have set up the necessary environment variables and successfully established a connection with firebase. However, I keep running into an error ...

What is the best way to interpret a JSON result?

I've encountered an issue while attempting to parse the JSON output of a command. The error message is as follows. I've also included a snippet of the sample output for reference. Can you provide any guidance on how to resolve this? import subpr ...

Using Angular to send JSON data to an API

I'm attempting to send JSON data to an API, but I'm encountering the following error... 405 (Method Not Allowed) Below is the JSON object I'm trying to send and the corresponding HTTP request... var productAttributes = { "CostRequire ...

Styling a Pie or Doughnut Chart with CSS

I am working on creating a doughnut chart with rounded segments using Recharts, and I want it to end up looking similar to this: Although I have come close to achieving the desired result, I am encountering some issues: Firstly, the first segment is over ...