Accessing data in a strangely formatted JSON file in JavaScript - javascript

I was given the following JSON format and I am having a difficult time getting to the information. I want to put it into a data table.
"data": {
"HeadingOne":{
"Columns":["Row1", "Row2"],
"Data":[["firstData", "secondData"]]
}
}
I am told that I should be able to access this data but I have absolutely no clue how to get to "firstData" in datatables. (from datatables.net) This is what I have tried
$(document).ready(function() {
$('#example').dataTable( {
"ajax": "<%= request.getContextPath()%>/ajax/mastermenu.txt",
"columns":[
{"data": "HeadingOne.Data.Row1"}
]
} );
} );
HTML:
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Row1</th>
<th>Row2</th>
</tr>
</thead>
</table>

As others have noted, you're missing a } at the end. After you fix that this should work.
Assuming the object is called data, this will get you "firstData"
console.log(data.HeadingOne.Data[0][0]); // "firstData"

Yeuch. But:
var data = {
"HeadingOne":{
"Columns":["Row1", "Row2"],
"Data":[
["firstData", "secondData"]
]
}
}
var firstData = data['HeadingOne']['Data'][0][0]
Note: I had to add a final } to that block otherwise it was not valid
If you're trying to access firstData by name, hopefully it's obvious that it won't work as it's contained in an array within an array (hence the [0][0]).

Related

Getting data from JSON and formatting this into a table

I am getting a little stuck with this one. I am trying to use javascript on my website to convert my API JSON data to a table. Without using an array in an array of data in JSON, it works fine which each item on a new line but soon as I use an nested array of data in there, it has all the data on one line, seperated by a comma. Thinking a for loop would work here but i'm not 100% sure if this is the best method.
I have tried multiple searches online and tested around myself but I can't seem to get it to work.
The following is simple version of the JSON data I am working with:
MACLIST = ["ABC","DEF"]
IPLIST = ["10.10.10.10","20.20.20.20"]
ZONELIST = ["Inside","Outside"]
var json = [{"MAC":MACLIST,"IP":IPLIST,"ZONE":ZONELIST},{"SOMETHING ELSE":"OK"}];
Script used:
$(document).ready(function () {
ko.applyBindings({
teams: json
});
});
HTML used:
<table>
<thead>
<tr>
<th>Device</th>
<th>IP</th>
<th>Zone</th>
</tr>
</thead>
<tbody data-bind="foreach: teams">
<tr>
<td data-bind="text: MAC"></td>
<td data-bind="text: IP"></td>
<td data-bind="text: ZONE"></td>
</tr>
</tbody>
</table>
Working JSON version (without nested array data) works:
var json = [{"MAC":"ABC","IP":"10.10.10.10","ZONE":"Inside"},{"MAC":"DEF","IP":"20.20.20.20","ZONE":"Outside}];
Any tips or advice would be greatly appreciated
Testing URL JSFiddle Link
You can map over each row to create a string of html for each row. Then inside each row, map over each column to create the string of html for each cell.
var json = [{
"MAC": "ABC",
"IP": "10.10.10.10",
"ZONE": "Inside"
}, {
"MAC": "DEF",
"IP": "20.20.20.20",
"ZONE": "Outside"
}];
const makeCell = (content) => {
return `<td>${content}</td>`
}
const makeRow = (content) => {
return `<tr>${content}</tr>`
}
const table = document.querySelector('.table')
const colHeaders = Object.keys(json[0]).map(key => makeCell(key)).join('')
const bodyRows = json.map(row => {
return makeRow(Object.keys(row).map(col => makeCell(row[col])).join(''))
}).join('')
document.querySelector('thead tr').innerHTML = colHeaders
document.querySelector('tbody').innerHTML = bodyRows
<table>
<thead>
<tr></tr>
</thead>
<tbody>
</tbody>
</table>
Hopefully this article will help you resolve the problem
https://www.geeksforgeeks.org/how-to-convert-json-data-to-a-html-table-using-javascript-jquery/

Dynamic JSON object to Html Table

I have gone through this solution Parsing JSON objects for HTML table . But in this solution Object keys are pre-defined when creating table. But I have some json data which can have random data.
Somtimes it can be :
var data = {
"C#": 2172738,
"CSS": 9390,
"HTML": 135085,
"Java": 337323
}
Or, Sometimes it can be:
var data = {
"Go": 2172738,
"Ruby": 9390,
"Dart": 135085
}
That means keys are not fixed. That data object can be dynamic. I want to convert the dynamic object to html table. Let's say, I have a table where thead is defined and tbody is empty:
<table id="_myTable">
<thead>
<th>Language</th>
<th>Line of Codes</th>
</thead>
<tbody>
</tbody>
</table>
How should I approach to insert that dynamic object data to tbody.
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>
You can use Object.keys(data) to get all of keys for "language" table data and Object.values(data) or Object.keys(data).map(key => data[key]) for "line of codes" table data.

How to display Java Hashmap.keySet() in a bootstrap table, from a java rest service?

i'm trying to display a hashmap keyset in a bootstrap table, but only the first character is showing.
This is my rest service function:
#GET
#Path("getquizes")
#Produces(MediaType.APPLICATION_JSON)
public Collection<String> getQuizes() {
System.out.println(activeQuizes.keySet());
return activeQuizes.keySet();
}
It is working. This is what i am receive:
Received Json object
Here is my Html:
<table data-toggle="table" id="tablequizes" class="display table table-bordered">
<thead>
<tr>
<th datatype="String">Name</th>
</tr>
</thead>
</table>
And my javascript:
function fetchQuizes() {
$.ajax({
url: 'rest/Quiz/getquizes',
type: 'GET',
datatype: 'json',
success: function (data) {
console.info(data);
$('#tablequizes').bootstrapTable('load', data);
},
error: function (result) {
console.info(result.responseText);
}
});
}
But the result is only showing the first character in the array:
Bootstrap datatable with hashmap keyset
I think you are getting wrong about what the keySet() is giving you:
Returns a Set view of the keys contained in this map.
You are getting only the key and not the value of the map. For getting the value use values()
Returns a Collection view of the values contained in this map
activeQuizes.values(); //Try with this.
You can try changing your ajax output content tablequizes to an Array with some name id in it in your JS.
Eg: [ {"name": "Quiz1"}, {"name": "Quiz2"} ]
And modify the th tag
<th data-field="name">Name</th>
This should solve your problem.

ng:repeat not loading data

This is my controller function to get data from server.
function carsController($http, $scope, $timeout) {
var vm = this;
vm.getCarData = getCarData;
function getCarData(){
$http.get('/api/getData').then(function (response) {
console.log(response.data.message);
vm.list = response.data.message;
});
}
}
Here is the data returned.
{
"message":[
{
"emp_id":1,
"emp_name":"toyota",
"city":"city1",
"nic_no":4554
},
{
"emp_id":2,
"emp_name":"sunny",
"city":"city2",
"nic_no":57412
},
{
"emp_id":3,
"emp_name":"tata",
"city":"city3",
"nic_no":1234
}
]
}
and html code to show data. I am using carsController as cars
<div class="row" data-ng-init="cars.getCarData()">
<div class="panel panel-default">
<table class="table table-bordered table-hover">
<tr>
<th>Name</th>
<th>Pages</th>
</tr>
<tr ng:repeat="vehicle in cars.list track by $index">
<td>{{vehicle.emp_name}}</td>
<td>{{vehicle.city}}</td>
</tr>
</table>
</div>
</div>
instead of showing data, UI show 100+ empty rows when page loaded.
What could be the issue?
UPDATED
If I manually set value as below, This works well.
vm.list = [
{
"emp_id":1,
"emp_name":"toyota",
"city":"city1",
"nic_no":4554
},
{
"emp_id":2,
"emp_name":"sunny",
"city":"city2",
"nic_no":57412
},
{
"emp_id":3,
"emp_name":"tata",
"city":"city3",
"nic_no":1234
}
];
the issue is, as you can see in the console log you have posted, response.data.message is an object. Not an array.
Try this instead
vm.list = response.data.message.message;
The following will bind the message array
You have two problems.
You are assigning vm.list to response.data.message, which, as NJ_93 points out, is an object. Use
vm.list = response.data.message.message;
You're not calling your getCarData() function from your controller. So the data is never fetched.
Are you sure that the problem is not because of you have used two different objects. vm.list for receiving the data from $http and using cars.list for ng-repeat
store data to $scope.vm.list
and in the UI use ng-repeat="cars in vm.list track by $index"

Put data from url into dataTable

I got this table code
<table id="tabel_komponen" class="table table-hover">
<thead>
<tr>
<th>ID Komponen</th>
<th>Nama Komponen</th>
<th>Ekuivalen SKS</th>
<th>Ekuivalen Jam</th>
<th>Indikator</th>
</tr>
</thead>
<tbody id="badan_tabel" >
</tbody>
</table>
And I use the dataTable Plugin to make it looks good, here's the code
$(document).ready( function () {
$('#tabel_komponen').DataTable();
} );
I want to get the data for the table from this URL : http://paramadina.net:18011/data/psc_komponen
I already try this code
$(document).ready( function () {
$('#tabel_komponen').DataTable();
} );
var table = $('#tabel_komponen').DataTable( {
ajax: 'data.json'
} );
alert( 'http://paramadina.net:18011/data/psc_komponen'+table.ajax.url() );
but it dont worked...And I want to add an edit button into the table
Thanks!!!!
If http://paramadina.net:18011/data/psc_komponen/data.json is the URL where JSON file is located, then use the code below:
$(document).ready( function () {
$('#tabel_komponen').DataTable({
ajax: 'http://paramadina.net:18011/data/psc_komponen/data.json'
});
});
As noted by #davidkonrad, unless paramadina.net allows cross-domain requests, the code above will fail. You need to allow such requests or use JSONP or other alternative methods to get the data.

Categories