Displaying JSON information in an HTML table with JavaScript

I successfully displayed JSON data in an HTML table. Here is the snippet I used:

$("#example-table").tabulator({
  height:"300px",
  fitColumns:true,
  tooltips:true,
  columns:[
    {title:"Month", field:"Month", sorter:"string"},
    {title:"Numbers", field:"numbers", width:400, sorter:"string"},
  ],
});

var sampleData= [
  {Month:"January", numbers:"124010"},
]

$("#example-table").tabulator("setData", sampleData);

$(window).resize(function(){
  $("#example-table").tabulator("redraw");
});
<html>
  <head>
<script   src="https://code.jquery.com/jquery-2.2.4.min.js"   integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="   crossorigin="anonymous"></script>
<script   src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"   integrity="sha256-eGE6blurk5sHj+rmkfsGYeKyZx3M4bG+ZlFyA7Kns7E="   crossorigin="anonymous"></script>

    <link rel="stylesheet" href="https://cdn.rawgit.com/olifolkerd/tabulator/master/tabulator.css">
    <script type="text/javascript" src="https://cdn.rawgit.com/olifolkerd/tabulator/master/tabulator.js"></script>
  </head>
  <body>
    <div id="example-table"></div>
  </body>
</html>

Recently, I received the JSON data in a new format. Previously it was structured as follows:

{Month:"January", numbers:"124010"},
 {Month:"February", numbers:"545010"}

Now, the format is different :

{"headers":["Month","numbers"],"rows":[["January",124010],["February",545010]]}

I attempted to parse this new data without success using the following code snippet:

$("#example-table").tabulator({
  height:"300px",
  fitColumns:true,
  tooltips:true,
  columns:[
    {title:"Month", field:"Month", sorter:"string"},
    {title:"Numbers", field:"numbers", width:200, sorter:"string"},
  ],
});

var data= {"headers":["Month","numbers"],"rows":[["January",124010],["February",545010]]}

var finaldata = [];
for (var i = 0; i < data.rows.length; i++) {
finaldata.push(data.rows[i][1])
}


$("#example-table").tabulator("setData", finaldata);

$(window).resize(function(){
  $("#example-table").tabulator("redraw");
});
<html>
  <head>
<script   src="https://code.jquery.com/jquery-2.2.4.min.js"   integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="   crossorigin="anonymous"></script>
<script   src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"   integrity="sha256-eGE6blurk5sHj+rmkfsGYeKyZx3M4bG+ZlFyA7Kns7E="   crossorigin="anonymous"></script>

    <link rel="stylesheet" href="https://cdn.rawgit.com/olifolkerd/tabulator/master/tabulator.css">
    <script type="text/javascript" src="https://cdn.rawgit.com/olifolkerd/tabulator/master/tabulator.js"></script>
  </head>
  <body>
    <div id="example-table"></div>
  </body>
</html>

Case 1 :

I encountered difficulties parsing the new JSON format. Any suggestions for resolving this issue?

Case 2 :

Consider converting the multidimensional JSON format to the one used in the initial snippet. From a multidimensional JSON structure to a flat one.

Conversion steps:

{"headers":["Month","numbers"],"rows":[["January",124010],["February",545010]]}

to

{Month:"January", numbers:"124010"},
{Month:"February", numbers:"545010"}

If modifying the current script is not feasible, would it be worthwhile trying to convert the JSON format?

Answer №1

If the headers remain constant, you can easily loop through all rows and create new objects from them.

var unformatted = {
    "headers": [
        "Month",
        "numbers"
    ],
    "rows": [
        [
            "January",
            124010
        ],
        [
            "February",
            545010
        ]
    ]
};

var formatted = [];

for (var i = 0; i < unformatted.rows.length; i++) {
    var row = unformatted.rows[i];
    
    formatted.push({
        Month: row[0],
        numbers: row[1]
    });
}

console.log(formatted);

To handle dynamic headers that may change in the future as per the comments, use the code below.

var unformatted = {
    "headers": [
        "Month",
        "numbers",
        "another_column"
    ],
    "rows": [
        [
            "January",
            124010,
            "Hello"
        ],
        [
            "February",
            545010,
            "World!"
        ]
    ]
};

var formatted = [];

for (var i = 0; i < unformatted.rows.length; i++) {
    var row = unformatted.rows[i],
        newObject = {};
    
    for (var j = 0; j < unformatted.headers.length; j++) { 
        newObject[unformatted.headers[j]] = row[j];
    }
    
    formatted.push(newObject);
}

console.log(formatted);

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

How can I customize the appearance of a checkbox button in JavaFX?

I am currently working on styling a JavaFX scene with CSS in a stylesheet. The goal is to apply styles to all the "basic" elements of the scene when it loads. My issue lies in finding the correct code combination to change the background color of a button ...

Creating a distinctive property with the standard settings

How can we ensure a unique property is generated for a mongodb/mongoose model upon creation? What would be the most effective method to verify if the created value is not already in use and generate an alternative value before saving? let schema = new S ...

Image caption dynamically updated to match thumbnail caption using jQuery upon click event

My goal is to dynamically load the data-caption of thumbnail images when clicked, and then update the main image's data-caption when the main image is changed with a thumb image. I am currently struggling to make the data-caption update along with the ...

Can transclusion be achieved while maintaining the directive's scope in Angular?

Can we achieve the following functionality in Angular? <div ng-controller="MainCtrl" ng-init="name='World'"> <test name="Matei">Hello {{name}}!</test> // I expect "Hello Matei" <test name="David">Hello {{name}}!&l ...

Error encountered while deserializing Json in C#: Null class

My PHP code is working perfectly fine and returning the correct JSON response: if ($result->num_rows === 1) { $sql = ("SELECT username, email, plan, activationdate, terminationdate FROM users WHERE username = '$username' LIMIT 1" ...

Concatenate strings in Angular 5 only when the specified field is present in the HTML

I need help with concatenating two fields, but the issue arises when the second field is missing. Specifically, the group.GroupDescription field may not be present in some entries. Is there a way to concatenate both fields only if the second field group.Gr ...

Guide on retrieving JSON information within an array utilizing a loop function

Hey everyone, I'm facing an issue and I could really use some help. I'm new to working with ajax processing and I'm stuck on a problem. I have successfully retrieved ajax data and now I need to store it in an array. My goal is to populate a ...

Can you provide a solution in C# for traversing through article elements within the HTML of a website?

I need assistance with iterating through elements on a webpage that are all categorized under the html <article> tag. How can I achieve this? <article> <div class="inner-article"> <a style="height:150px;" href="/shop/jackets/v87vh6 ...

The combination of Node.js module.exports and shorthand ternary operators for conditional statements

Can you explain the purpose of this line 'undefined' != typeof User ? User : module.exports and why is everything enclosed within (function(){})? I am having trouble understanding its significance. This code snippet is extracted from a library f ...

Align the image and caption at the center in Bootstrap 4

I am presenting a figure that includes an image along with a caption. Here is the code for reference: <figure class="figure"> <img src="../img/atmpressure.svg" class="figure-img img-fluid" alt="pressue plot"> <figcaption class="figure-c ...

Managing numerous requests simultaneously without causing one to delay or block the others

I am facing challenges when it comes to managing multiple client requests. Ideally, each route should be handled asynchronously, but I am struggling to handle one request after another without the previous one interfering with the next one. In the code sni ...

Having trouble with Vuex actions. Getting an error message that says "Failed to signInWithEmailAndPassword: The first argument "email" must be a valid string."

I recently started exploring Vuejs state management. I attempted to create a login system with Firebase using Vuex. However, I encountered the following error: signInWithEmailAndPassword failed: First argument "email" must be a valid string I'm havi ...

Creating a dynamic Bootstrap 4 hover effect for collapsible elements with numerous items

I have come across a few techniques for implementing the collapsible accordion feature in bootstrap. However, I am facing a challenge when it comes to customizing it so that only one panel-collapse is activated upon hovering over the div.panel-heading > ...

Ensure that each component in Angular2 includes a separate JavaScript file

Every time I include a JavaScript file in my index.html and use a function, it only works the first time. When I refresh the page, it stops working. I am looking for a solution to include a JavaScript file for each component to prevent this issue from oc ...

Spacing between navigation items

After working on my navigation menu locally, I noticed that when I uploaded it online, some changes didn't take effect on Chrome and the design on Firefox was different from what I intended. I'm not sure what I might be doing wrong here. Here is ...

Unable to construct React/Next project - identified page lacking a React Component as default export (context api file)

When attempting to compile my Next.js project, I encountered an error message in the terminal: Error: Build optimization failed: found page without a React Component as default export in pages/components/context/Context The file in question is utilizing ...

What is the best way to add spacing between the fields within a Bootstrap 4 form row that spans across 2 rows when viewed on small displays?

Trying to create a bootstrap 4 form with fields in one row for larger screens and two rows for smaller screens. The attempt was made using the following code: <div class="form-group row"> <label class="col-sm-2 col-form-label">File:</lab ...

What is the most effective method for implementing a background repeated image in Foundation 4 framework?

Currently, I am utilizing the foundation4 framework for my website. In order to achieve a repeating tiled background, I have crafted a custom CSS file and included the following code snippet: body { background: url(img/floorboardsbg.jpg) repeat; } Whi ...

Discovering how to retrieve data from a JSON response in Postman that includes a key with a period in it

When working with JSON responses in Postman, it's usually easy to retrieve a value for a key. For example: pm.test("AddCluster", function () { var jsonData = pm.response.json(); pm.globals.set("taskIdCluster", jsonData.value); }); Consid ...

What is the correct method to sanitize the data obtained from a text area before inserting it back into the same text area?

When a user enters text into a textarea, it is directly inserted into a mySQL database. To ensure its security, I apply trim, htmlentities, mysql_real_escape_string functions to sanitize the input. Additionally, magic quotes are enabled. However, when it c ...