logo
down
shadow

Dynamic JSON object to Html Table


Dynamic JSON object to Html Table

Content Index :

Dynamic JSON object to Html Table
Tag : javascript , By : ponchopilate
Date : January 12 2021, 01:40 AM

will be helpful for those in need You can use for...in, Template literals and element.insertAdjacentHTML(position, text); to accomplish your task:
var data = {
    "C#": 2172738,
    "CSS": 9390,
    "HTML": 135085,
    "Java": 337323
}
for (key in data) {
    var tr = `<tr><td>${key}</td><td>${data[key]}</td></tr>`;
    document.querySelector('#_myTable tbody').insertAdjacentHTML('beforeend', tr);
}
<table id="_myTable">
    <thead>
    <th>Language</th>
    <th>Line of Codes</th>
    </thead>
    <tbody>
    </tbody>
</table>

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

dynamic html table with complex JSON


Tag : jquery , By : Xander
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further I have an aspx page, which is calling a ajax method to return a JSON object containing arrays of Countries. , get this inside your for loop:
for (var i = 0; i < tdata.length; i++) {
    response += '<div class="item">' +

    '<table  class="table table-user-information" style="height: 300px;">' +
    '<tbody>' +
    '<tr>' +
    '<td><label>Countries</label></td>' +
    '<td><ul>';

    $.each(tdata[i]['Countries'], function (index, value) {
        response += '<li>' + value + '</li>';
    });

    response += '</ul></td></tr>' + '</div>';
}

How to convert dynamic JSON to an HTML table


Tag : chash , By : Picoman Games
Date : March 29 2020, 07:55 AM
it should still fix some issue I found the best way to do this would be using Newtonsoft.Json to dynamically parse the data and being able to format it easily.
Main View:
@{
    var converted = JsonConvert.DeserializeObject(Model.JsonData);
    if (converted is JObject)
    {
        isMultiLevel = true;
    }
    else if (converted is JArray)
    {
        isSingleLevel = true;
    }
}

@if (isMultiLevel)
{
    Html.RenderPartial("Details_MultiLevelResult", Model);
}
else if (isSingleLevel) //might not be multiLevel nor singleLevel (if no data)
{
    Html.RenderPartial("Details_SingleLevelResult", Model);
}
@{
    JObject json = JsonConvert.DeserializeObject(Model.JsonData) as JObject;
}

<table class="display table table-striped table-bordered" cellspacing="0" style="background-color: white;">
    <tbody>
        @foreach (var property in json.Properties())
        {
            <tr>
                <td><b>@property.Name</b></td>
                <td>
                    @foreach (var data in property)
                    {
                        if (data.Type == JTokenType.Array)
                        {
                            <table class="table table-bordered">
                                <thead>
                                    <tr>
                                        @{
                                             var firstProperty = data.First;
                                        }
                                        @if (firstProperty != null)
                                        {
                                            foreach (JProperty propertyData in firstProperty)
                                            {
                                                <th>@propertyData.Name</th>
                                            }
                                        }
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach (var propertyData in (data as JArray))
                                    {
                                        <tr>
                                            @foreach (JProperty jProperty in propertyData)
                                            {
                                                if (jProperty.HasValues)
                                                {
                                                    if (jProperty.Value.Type == JTokenType.Object)
                                                    {
                                                        var inlineClass = ((JObject)jProperty.Value).Properties();
                                                        var result = inlineClass.Select(x => string.Format("<div><b>{0}:</b><span> {1}</span></div>", x.Name, x.Value)).ToList();
                                                        string joinedResult = string.Join("", result);
                                                        <td>
                                                            <div>@Html.Raw(joinedResult)</div>
                                                        </td>
                                                    }
                                                    else
                                                    {
                                                        <td>@jProperty.Value</td>
                                                    }
                                                }
                                            }
                                        </tr>
                                    }
                                </tbody>
                            </table>
                        }
                        else if (data.Type == JTokenType.Object)
                        {
                            var uniqueClass = data as JObject;

                            <table class="table" style="background-color: white;">
                                <thead>
                                    <tr>
                                        @{
                                            var classProperties = uniqueClass.Properties()
                                                .Select(x => x.Name)
                                                .ToList();
                                            foreach (var classProperty in classProperties)
                                            {
                                                <th>@classProperty</th>
                                            }
                                        }
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        @foreach (var classProperty in uniqueClass.Properties())
                                        {
                                            if (classProperty.Value.Type == JTokenType.Object)
                                            {
                                                var inlineClass = ((JObject)classProperty.Value).Properties();
                                                var result = inlineClass.Select(x => string.Format("<div><b>{0}</b> <span>: {1}</span></div>", x.Name, x.Value)).ToList();
                                                string joinedResult = string.Join("", result);
                                                <td>
                                                    <div>@Html.Raw(joinedResult)</div>
                                                </td>
                                            }
                                            else
                                            {
                                                <td>@classProperty.Value</td>
                                            }
                                        }
                                    </tr>
                                </tbody>
                            </table>
                        }
                        else
                        {
                            @data
                        }
                    }
                </td>
            </tr>
        }
    </tbody>
</table>
@{
    JArray jsonAsArray = JsonConvert.DeserializeObject(Model.JsonData) as JArray;

    var classes = jsonAsArray
        .OfType<JObject>()
        .ToList();
    var nonClasses = jsonAsArray
        .Where(x => x.Type != JTokenType.Object)
        .ToList();
}

<table class="table" style="background-color: white;">
    <thead>
        <tr>
            @{
                var anyClass = classes.FirstOrDefault();
                if (anyClass != null)
                {
                    var properties = anyClass.Properties().Select(x => x.Name).ToList();
                    foreach (var property in properties)
                    {
                        <th>@property</th>
                    }
                }
                else
                {
                    <th>Data</th>
                }
            }
        </tr>
    </thead>
    <tbody>
        @foreach (JObject item in classes)
        {
            <tr>
                @foreach (var property in item.Properties())
                {
                    if (property.Value.Type == JTokenType.Array)
                    {
                        var model = new MyModel();
                        model.JsonData = property.Value.ToString();
                        <td>
                            @Html.Partial("Details_SingleLevelResult", model)
                        </td>
                    }
                    else if (property.Value.Type == JTokenType.Object)
                    {
                        var inlineClass = ((JObject)property.Value).Properties();
                        var resultado = inlineClass.Select(x => string.Format("<div><b>{0}</b> <span>: {1}</span></div>", x.Name, x.Value)).ToList();
                        string resultadoUnido = string.Join("", resultado);
                        <td>
                            <div>
                                @Html.Raw(resultadoUnido)
                            </div>
                        </td>
                    }
                    else
                    {
                        <td>@property.Value</td>
                    }
                }
            </tr>
        }
        @foreach (JValue item in nonClasses)
        {
            <tr>
                <td>@item.Value</td>
            </tr>
        }
    </tbody>
</table>

HTML table formatting issue - parsing jSON object into an HTML table


Tag : javascript , By : tayles
Date : March 29 2020, 07:55 AM
To fix this issue The problem is that you're adding rows to your existing rows.
In addition to this, you are considering the table to be one singular 'object', and are adding both the rows and the cells directly to the table. The table cells should be added to their containing rows.
var product = {
  "name": "Product1",
  "model": "1852ak",
  "year": "2016",
  "details": "refurbished"
}

$(document).ready(function() {
  var table = $('#sample');
  var row1 = $('<tr>');
  var row2 = $('<tr>');
  var row3 = $('<tr>');
  row1.append('<td colspan = 2>' + product.name + '</td>');
  table.append(row1);
  row2.append('<td>' + product.model + '</td>');
  row2.append('<td>' + product.year + '</td>');
  table.append(row2);
  row3.append('<td colspan = 2>' + product.details + '</td>');
  table.append(row3);
});
td {
  border: 1px solid black;
  text-align: center;
  padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="sample"></table>

Making a dynamic HTML table using json


Tag : javascript , By : Salikh
Date : March 29 2020, 07:55 AM
wish of those help This is a plain JS solution. The JSON is parsed as a JSON object. I edited your HTML and added some new elements with an ID to select them from within JavaScript.
I edited my answer. NEVER use id multiple times. I changed it to a CSS class. Align should be correct now.
var data = JSON.parse(`{
    "header": {
        "invoice": "59",
        "name": "Morning Cafe",
        "address": "Main Road, Kandawala",
        "contact": "111-555-978",
        "date": "12/11/2018 01:28:52",
        "counter": "SAKTHY"
    },
    "items": [{
        "no": "1",
        "item": "Pizza",
        "code":"PZ4566",
        "price": "500.00",
        "qty":"2",
        "amount":"1000.00"
    },
    {
        "no": "2",
        "item": "Burger",
        "code":"BR4587",
        "price": "250.00",
        "qty":"2",
        "amount":"500.00"
    },
    {
        "no": "3",
        "item": "Sample",
        "code":"SE2569",
        "price": "50.00",
        "qty":"5",
        "amount":"250.00"
    }],
    "footer": {
        "total":"1750.00",
        "cash":"2000.00",
        "balance":"250.00",
        "notice": "In case of a price discrepancy, return the bill and item within 2 days to refund the difference."
    }
    }`);

document.getElementById('invoice-name').innerHTML  = data.header.name;
document.getElementById('invoice-address').innerHTML  = data.header.address;
document.getElementById('invoice-contact').innerHTML  = data.header.contact;
document.getElementById('invoice-date').innerHTML  = data.header.date;
document.getElementById('invoice-counter').innerHTML  = data.header.counter;
document.getElementById('invoice-no').innerHTML  = data.header.invoice;

var insertAtRow=5;
var table = document.getElementById("invoice-table");
for(var i = data.items.length-1; i >=0 ;i--)
{
	var item = data.items[i];
  var rowHead = table.insertRow(insertAtRow);
	var rowItem = table.insertRow(insertAtRow+1);
	
  rowHead.insertCell(0).innerHTML = item.no;
  rowHead.insertCell(1).innerHTML = item.item;
  
  rowItem.insertCell(0).innerHTML = "";
	rowItem.insertCell(1).innerHTML = item.code;
	rowItem.insertCell(2).innerHTML = item.qty;
  
  var priceCell = rowItem.insertCell(3);
  var amountCell = rowItem.insertCell(4);
  priceCell.innerHTML = item.price;
  amountCell.innerHTML = item.amount;
  priceCell.classList.add('aliRight');
  amountCell.classList.add('aliRight');
}

document.getElementById('footer-net-total').innerHTML  = data.footer.total;
document.getElementById('footer-cash').innerHTML  = data.footer.cash;
document.getElementById('footer-balance').innerHTML  = data.footer.balance;
document.getElementById('footer-notice').innerHTML  = data.footer.notice;
<html>
   <head>
      <title>Hello</title>
      <style>
         table{
         font-family: 'Courier New', Courier, monospace;
         }
         .aliCenter{
         text-align:center;
         }
         .aliRight{
         text-align:right;
         }
         td#myId{
         text-align:center;
         font-size: 13px;
         }
      </style>
   </head>
   <body>
      <table id="invoice-table" width="302.362205"> <!-- To print paper size is 80 cm (=302.362205 pixel) -->
         <!-- header -->
         <tr>
            <td colspan="5" class="aliCenter">
              <div id="invoice-name"></div>
              <div id="invoice-address"></div>
              <div id="invoice-contact"></div>
            </td>
         </tr>
         <tr>
            <td colspan="5" id="myId"><span id="invoice-date"></span>&nbsp;&nbsp;<span id="invoice-counter"></span>&nbsp;&nbsp;No: <span id="invoice-no"></span></td>
         </tr>
         <tr>
            <td colspan="5">
               <hr>
            </td>
         </tr>
         <tr>
            <td class="aliCenter">NO</td>
            <td class="aliCenter">ITEM</td>
            <td class="aliCenter">QTY</td>
            <td class="aliCenter">PRICE</td>
            <td class="aliCenter">AMOUNT</td>
         </tr>
         <tr>
            <td colspan="5">
               <hr>
            </td>
         </tr>
         <!-- buying items -->
         <!--Script will insert after 6th row!!!-->
         <!-- footer -->
         <tr>
            <td colspan="5">
               <hr>
            </td>
         </tr>
         <tr>
            <td></td>
            <td colspan="3">Net Total</td>
            <td class="aliRight"><span id="footer-net-total"></span></td>
         </tr>
         <tr></tr>
         <tr>
            <td></td>
            <td colspan="3">Cash</td>
            <td class="aliRight"><span id="footer-cash"></span></td>
         </tr>
         <tr>
            <td></td>
            <td colspan="3">Balance</td>
            <td class="aliRight"><span id="footer-balance"></span></td>
         </tr>
         <tr></tr>
         <tr>
            <td colspan="5" class="aliCenter">-------IMPORTANT NOTICE-----------</td>
         </tr>
         <tr>
            <td colspan="5" class="aliCenter"><span id="footer-notice"></td>
         </tr>
      </table>
   </body>
</html>

JSON to Dynamic HTML Table in Angular


Tag : angular , By : user171555
Date : March 29 2020, 07:55 AM
should help you out How to create Dynamic Html Table with Column and row ? Below is the JSON data and I want to create HTML table using this data : , Suppose your json is stored in data,
Try like this:
<table>
    <tr>
        <th *ngFor="let item of data.columnNames">{{item}}</th>
    </tr>
    <tr *ngFor="let rowData of data.rows">
        <td *ngFor="let el of rowData">{{el}}</td>
    </tr>
</table>
Related Posts Related QUESTIONS :
  • applying texture to custom plane geometry in Threejs
  • How do I pass an Event as a function parameter in HTML written inside JavaScript variable?
  • Interface of object parameter with default value and default property
  • Does using try / catch rather than `.catch` observable operator with XHR requests reduce performance?
  • In IE11 background colors not working on printing
  • TypeScript interface signature "(): string"
  • Is synchronous XMLHttpRequest supported in Internet Explorer 10 and 11?
  • Axios function not returning any values with js
  • How to use firestore TIMESTAMP to create time-stamp in JavaScript
  • Instantiate subclass without constructing
  • Outputing a created object in javascript to a server side JSON file
  • Transition the numeric labels in a bar chart
  • createBottomTabNavigator: hide just one tab from the tabBar
  • iife vs simple statement behavior with document.title
  • showDialogPopup Refresh Page after Click
  • Child component does not set the initial value passed from the parent: ReactJS
  • Nodejs javascript added to button not responding
  • Trying to define a promise.all
  • Python GEE to extract featurecollection timeseries from Landsat imageries
  • How to write negative binary number?
  • Unable to set property of individual object
  • Why Named Function Expression itself cannot assign Name to another Value?
  • How to reset scroll position on single page pagination
  • How to scroll to bottom of page, when a new message is sent - Socket.io
  • How to reconstruct audio blob from a base64 encoded String?
  • How to calculate numbers within an array of objects
  • Using JavaScript to change CSS properties of SVG circles for all circles that was not clicked
  • Is there value in propTypeing repeat required properties at every level of nested components?
  • Call function if variable does not exist in a filter
  • localStorage value doesn't get updated automatically
  • React not updating state with setState correctly inside promises
  • Direct native JavaScript or jQuery method to get containing block of an element
  • How to send Id and file to same controller?
  • How to Make a jQuery Table Cell(td) clickable to Run a Function?
  • Prevent the duplicate function onchange event jQuery
  • Reactjs Input Upload doesn't return local URL
  • An unexpected 'StartObject' node was found when reading from the JSON reader. A 'PrimitiveValue' node was expected
  • How to filter a JSON Array, with an eventListener input value at keyup
  • How to separate the different properties of filter in css?
  • Why dont work change event of bootstrap input spinner?
  • How to hide overflow text content in react
  • Is there another way to write line 6
  • Cypress - how to find by text content?
  • How to setstate for the dynamic checkboxes in a loop in react?
  • Is display:none safe?
  • How to create a form to change part of a href url of a button?
  • Put many function inside function in Javascript
  • how to exit from loop after a ajax call
  • Do Angular Reactive Form Validator.min/max check Perform Type Conversions before checking the value?
  • How to Replace Text Within Script Tags Using JQuery
  • add variable to object if not undefined using short-hand
  • How can I effectively curve my items inside a list?
  • Add new record Keyboard Shortcut on Kendo Grid Mvc
  • Time and Date running on page
  • Looping through page links puppeteer doesn't return values from the newly loaded page
  • Problem with Navigator.geoLocation.getCurrentPosition not working
  • Trying to change the id of an element with Javascript
  • Embedded Schema Inserting Blank in Meteor using Collection2
  • avoid useEffect to render at first load?
  • Why is this CSS transition only working correctly on the some clicks? How to solve it?
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com