JSON Data Not Displaying Correctly in HTML - javascript

I Have a Simple JSON File With Data and I want to display that data in HTML website following is the JSON file :
[
{
Indice_Name: 'Nasdaq',
price: '13,017.79',
change: '+40.12 (+0.31%)'
},
{
'Indice_Name Name': 'FTSE',
price: '6,729.69',
'change%': '+54.86 (+0.82%)'
},
{
'Indice_Name Name': 'Dow_Jones',
price: '32,787.33',
'change%': '+167.85 (+0.51%)'
},
{
'Indice_Name Name': 'SGX_Nifty',
price: '9.91',
'change%': '-0.02 (-0.20%)'
},
{
'Indice_Name Name': 'Nikkei_225',
price: '29,176.70',
'change%': '+446.82 (+1.56%)'
}
]
Following is My HTML and Javascript File:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="World_Indice_DataDiv"></div>
<script>
fetch('http://127.0.0.1:5500/data/World_Indices_Display.json')
.then(function (response) {
return response.json();
})
.then(function (data) {
appendData(data);
})
.catch(function (err) {
console.log(err);
});
function appendData(data) {
var mainContainer = document.getElementById("World_Indice_DataDiv");
for (var i = 0; i < data.length; i++) {
var div = document.createElement("div");
div.innerHTML = 'Indice Name: ' + data[i].Indice_Name + '\n' + 'Price : ' + data[i].price + '\n' + data[i].change;
mainContainer.appendChild(div);
}
}
</script>
</body>
</html>
When i run this Following piece of code it doesnt show me the expected results:
How Can I Display The JSON Data Correctly?

Your JSON structure is not how it should be. If the first object is how it should be (judging by the fact that they are displayed correctly), the others should have the same property names.
In fact, the other objects (except the first one) all have a property called 'Indice_Name Name' but it should be 'Indice_Name'. They also have another property called "change%" when it should be "change" to match the first object.
You need to change the JSON file to this (the rest should follow the same structure):
[
{
"Indice_Name": "Nasdaq",
"price": "13,017.79",
"change": "+40.12 (+0.31%)"
},
{
"Indice_Name": "FTSE",
"price": "6,729.69",
"change": "+54.86 (+0.82%)"
},
.
.
.
]

There's one issue with your json array if you check the first item has by key Indice_Name and the rest are Indice_Name Name, so if this is your response you can handle it like this:
const arr = [
{
"Indice_Name": "Nasdaq", // <--- here's one of your problems with response
"price": "13,017.79",
"change": "+40.12 (+0.31%)"
},
{
"Indice_Name Name": "FTSE", // <--- and here, idk why you receive these
"price": "6,729.69",
"change%": "+54.86 (+0.82%)" // <--- you can access these keys with
// brackets operator obj['key'] in this
// case you must write item['change%']
// to get value. Not recommended 2 have
// such weird names as keys!
},
{
"Indice_Name Name": "Dow_Jones",
"price": "32,787.33",
"change%": "+167.85 (+0.51%)"
},
{
"Indice_Name Name": "SGX_Nifty",
"price": "9.91",
"change%": "-0.02 (-0.20%)"
},
{
"Indice_Name Name": "Nikkei_225",
"price": "29,176.70",
"change%": "+446.82 (+1.56%)"
}
];
const div = document.getElementById('inner');
arr.forEach(item => {
// you can use backticks to make it easier
// since you're innering html you can use html tags to help you when
// displaying data!
div.innerHTML = `${div.innerHTML}
<p>Indice Name: ${item['Indice_Name'] || item['Indice_Name Name']}
<p>Price: ${item.price}</p>
<p>Change: ${item['change%']}</p>
<br>`
});
<div id="inner"></div>

I am now able to solve my problem,After looking at many answers on this question.Essentially the problem was that the keys of the JSON file were wrong and not similar to the first key of JSON file.After i fixed the JSON file the code started working properly.Hope this will help someone in future.
Correct JSON File:
[
{
Indice_Name: 'Nasdaq',
'price': '13,017.79',
'change': '+40.12 (+0.31%)'
},
{
'Indice_Name': 'FTSE',
'price': '6,729.69',
'change': '+54.86 (+0.82%)'
},
{
'Indice_Name Name': 'Dow_Jones',
'price': '32,787.33',
'change': '+167.85 (+0.51%)'
},
{
'Indice_Name': 'SGX_Nifty',
'price': '9.91',
'change': '-0.02 (-0.20%)'
},
{
'Indice_Name': 'Nikkei_225',
'price': '29,176.70',
'change': '+446.82 (+1.56%)'
}
]

Related

Making a gogocartojs map work in js project

I created a project and I'm trying to add gogocartoJs in it.
The project works but the map is not showing.
I tried with the guides I found in the site, it looks plain and easy, but there is an step that I'm not understanding (please dont just copy/paste a piece of the site like it was obvious what it is the mistake, because it is not for me)
<html lang="en">
<head>
<link
rel="stylesheet"
href="https://gogocarto.fr/assets/css/gogocarto.min.css"
/>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<script type="text/javascript" src="./jquery.js"></script>
<script src="https://gogocarto.fr/js/gogocarto.min.js"></script>
<title>Hello Webpack</title>
</head>
<body>
<div>
<h1>Hello Webpack</h1>
<div id="gogocarto"></div>
</div>
<script>
$(document).ready(function() {
carto = goGoCarto("#gogocarto", {
data: {
taxonomy: taxonomy,
elements: elements
}
});
});
</script>
<script src="./bundle.js"></script>
</body>
</html>
I expect the map to show, and it doesnt
I added the project to github to show better
https://github.com/Aredros/testGogo/tree/master/dist
elements & taxonomy are js variables containing data you must provide according to the format described in the documentation.
// taxonomy
let taxonomy = {
"options":[
{
"id": "eu1",
"name":"Belgium",
"color":"#9acd32",
"icon":"fa-solid fa-building"
},
{
"id": "eu2",
"name": "Netherland",
"color": "#ffa500",
"icon": "fa-solid fa-fan"
},
{
"id": "eu3",
"name": "Luxembourg",
"color": "#a52a2a",
"icon": "fa-solid fa-money-bill-1"
}
]
}
The only missing info in the documentation is the id key in the taxonomy which must be referenced in your elements source dataset.
// elements
let elements = [
{
"title": "Brussels",
"geo": {
"latitude":50.84,
"longitude":4.34
},
"taxonomy": [ "eu1" ],
},
{
"title": "Namur",
"geo": {
"latitude":50.45,
"longitude":4.88
},
"taxonomy": [ "eu1" ],
},
{
"title": "Liege",
"geo": {
"latitude":50.62,
"longitude":5.60
},
"taxonomy": [ "eu1" ],
},
{
"title": "Rotterdam",
"geo": {
"latitude":51.88,
"longitude":4.51
},
"taxonomy": [ "eu2" ],
},
{
"title": "Amsterdam",
"geo": {
"latitude":52.07,
"longitude":5.12
},
"taxonomy": [ "eu2" ],
},
]
Idealy you should build an API returning taxonomy classification & elements data. Then perform ajax call in your html page.
$.ajax({
type: 'GET',
url: '/ajax/url_to_get_elements',
dataType: 'json',
success: function(elements, status) {
build_map(elements);
}
});
// build map = function with 1 arguments (elements) where you put the call to goGoCarto and options...
You can define more than 1 taxonomy group (Example above is about English countries) with the name you want => Cfr. Advanced Taxonomy with Categories. Your elements can then have multiple taxonomy reference listed [ "eu1", "week22", 14 ]. Items in the list can be Integer or String. The only important thing is the ID key and the taxonomy order! Keep the same order in your taxonomy than in your key "taxonomy": in your elements data sources!
Point of attention
Because the library is highly configurable with options, colors and icons it is important to put all your <scripts> tags inside <head> tags of your html page!

print object data in table Jquery

Hi i wanna display some values of an object,
the object has the next structure:
{
0:
{ id: "value",
topic: "value",
description: "value",
...
}
1:
{
...
}
}
and this is my code for display in a table with id=cursos
it has an ajax call before so I do this inside .done() method
the thing is that when I use double each to call teh first object and display its attributes it doesn't show anything, but when I call them by its name, without $.each() it is showed in table format,
How can I show the values of my objects in table format using $.each(), just to save code lines note: i have also changed the .html() for .append() and it's the same result.
resultado.done(
function (data){//success
$("#cursos").append($("<tr>").append(
$("<td>").append("Tema"),
$("<td>").append("Indice"),
$("<td>").append("Descripción"),
$("<td>").append("Fecha"),
$("<td>").append("Idioma"),
$("<td>").append("Imagen"),
$("<td>").append("Enlaces"),
$("<td>").append("Nivel"),
$("<td>").append("Palabras clave"),
$("<td>").append("Autor"),
$("<td>").append("Escuela"),
$("<td>").append("Categoria"),
$("<td>").append("Subcategoria")
),
$("<tr>").html(
$.each(data, function (key, data1) {
$.each(data1, function (index, datos) {
console.log("index", datos);
$("<td>").append(datos);
})
})
/* if this block comment is removed it works
$("<td>").append(data[0].tema),
$("<td>").append(data[0].indice),
$("<td>").append(data[0].descripcion),
$("<td>").append(data[0].fecha),
$("<td>").append(data[0].idioma),
$("<td>").append(data[0].imagen),
$("<td>").append(data[0].enlaces),
$("<td>").append(data[0].nivel),
$("<td>").append(data[0].keywords),
$("<td>").append(data[0].autorId),
$("<td>").append(data[0].escuelasId),
$("<td>").append(data[0].categoriaId),
$("<td>").append(data[0].subcategoriaId)*/
)
);
//data[0].tema
}//function DONE
);//done
Try something like this:
var dataCollection = {
0: {
id: "id0",
topic: "topic0",
description: "desc0"
},
1: {
id: "id1",
topic: "topic1",
description: "desc1"
},
2: {
id: "id2",
topic: "topic2",
description: "desc2"
}
};
$.each(dataCollection, function(index) {
$("table#cursos").append("<tr>");
$.each(dataCollection[index], function(key, value) {
$("table#cursos").append("<td>" + value + "</td>");
});
$("table#cursos").append("</tr>");
});
See fiddle.
Hope this helps!
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8"/>
<!--http://stackoverflow.com/a/8563020/3200163-->
<!--http://stackoverflow.com/questions/8562744/how-to-loop-through-this-nested-object-json-array-and-build-an-html-string-with-->
</head>
<body>
<script type="text/javascript" src="scripts/jquery.js"></script>
<script>
var data = {
"sEcho": 1,
"total": "1710",
"aaData": [
[
"Help",
"http:\/\/www.mysite.com\/wp-content\/uploads\/2011\/09\/dt_intfc4e732d1f1276d_4e76fab1e95bd.mp3?King_of_Spain_Entropy_02_Animals_Part_1.mp3",
"1784",
"3",
0,
null,
"0000-00-00 00:00:00"
],
[
"A Day In The Life",
"http:\/\/www.mysite.com\/wp-content\/uploads\/2011\/09\/dt_intfc4e732d1f1276d_4e76f5fc253a1.mp3?JenWood_Zeppelin.mp3",
"3573",
"3",
0,
null,
"0000-00-00 00:00:00"
]
]
}
var str = "";
for (var item in data.aaData) {
str += '<tr>';
for (idata in data.aaData[item]) {
str += '<td>' + data.aaData[item][idata] + '</td>';
}
str += '</tr>';
}
$('body').append("<table>" + str + "</table>");
</script>
</body>
</html>
This code creates a table correctly :)

Free JQGrid - save-button in inlineNav not working when adding a second row

we've several Free JQGrids and a problem with adding new rows.
Click on the icon in inlineNav (ADD) a new row will be shown up, clicking the SAVE-Icon the first time works fine. But when adding a second row the Save-buttton in inlineNav will not work. Enter-key in the row works. After reload the whole grid, it will work only once again.
Following is the code of the grid
some defaults:
jQuery.extend($.jgrid.defaults,{
autowidth: true, pager:true, pgbuttons:false, pginput:false,
pgtext:false, datatype: "json", mtype: "POST",
rownumbers:true, rowNum:9999,
postData: {"savestate_encrypted" : function() {return $("input[name='savestate_encrypted']").val();}},
ondblClickRow: function (rowid, status, e) {
var $self = $(this), savedRow = $self.jqGrid("getGridParam", "savedRow");
if (savedRow.length > 0 && savedRow[0].id !== rowid) {
$self.jqGrid("restoreRow", savedRow[0].id);
}
$self.jqGrid("editRow", rowid, { focusField: e.target });
},
});
The grid itself:
jQuery("#grid").jqGrid({
url:"....",
jsonReader: {root: "resourceList"},
height: 500,
cmTemplate: { editable: true},
inlineEditing: {keys: true},
editurl: "....",
colModel:[ //Define Table Columns
{name: "name", label:"Name", key:true, hidden:false},
{name: "activeJobs", label:"aktive Jobs", width:250}
],
}).jqGrid("navGrid", {refresh:true, edit:false, del:true, search:false, add:false})
.jqGrid("inlineNav", {save:true, edit:true, add:true})
</script>
I've figured out that the line 15300 (sorry don't know how to find the branch version - 30.Jan 2017) in the grid source will set the "var ind" to false, when clicking on the button, pressing enter-key works perfect
var tmp = {}, tmp2 = {}, postData = {}, editable, k, fr, resp, cv, savedRow, ind = $self.jqGrid("getInd", rowid, true), $tr = $(ind),
opers = p.prmNames, errcap = getRes("errors.errcap"), bClose = getRes("edit.bClose"), isRemoteSave, isError,
displayErrorMessage = function (text, relativeElem)....
As a fast solution I wanted to subsribe on an event and reload the whole grid. But subscribe() seems to be gone (we are switching from the old struts-tag grid to javascript. I think bind is the correct way now, but which event?
ADDITION---------------------------
I've created a working code which will show a similiar problem without Ajax and Json. When clicking ADD, enter the values and then selecting SAVE in the inlineNav Bar everything is OK, but pressing ADD again, enter values and then select SAVE, the edit-mode will stay open. If you use the Enter-Key instead the SAVE-btn it will work.
<!DOCTYPE html>
<html lang="de"><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="js/jquery-3.1.1.min.js"></script>
<script src="js/jquery-ui.min.js"></script>
<script src="js/jquery.jqgrid.src.js"></script>
<link rel="stylesheet" href="js/jquery-ui.min.css">
<link rel="stylesheet" href="js/ui.jqgrid.min.css">
</head>
<script type="text/javascript">
/* DEFAULTS */
jQuery.extend($.jgrid.defaults,{
autowidth: true, // nutzt die ganze verfügbare Breite
pager:true, // Fusszeile -
pgbuttons:false, // - ohne Seitenkontrollbuttons
pginput:false, // - ohne Eingabefeld
pgtext:false, // - ohne Text
rownumbers:true, // immer Zeilennummern
rowNum:9999, // bis zu 9999 Zeilen
ondblClickRow: function (rowid, status, e) {
var $self = $(this), savedRow = $self.jqGrid("getGridParam", "savedRow");
if (savedRow.length > 0 && savedRow[0].id !== rowid) {
$self.jqGrid("restoreRow", savedRow[0].id);
}
$self.jqGrid("editRow", rowid, { focusField: e.target });
},
});
// For JSON Response
/* jQuery.extend($.jgrid.inlineEdit,{
restoreAfterError:false,
errorfunc: function( response )
{
var resp = response;
alert("error7");
return false;
},
successfunc: function( response )
{
var resp = response;
var hasNoError = true;
// var hasNoError = (resp.responseJSON.actionErrors.length == 0);
return hasNoError;
}
});
*/
function dataset() {
"use strict";
var mydata2 = [
{ id: "10", name: "test" , value: "5"},
{ id: "20", name: "test20", value: "5"},
{ id: "30", name: "test30", value: "5"},
{ id: "40", name: "test40", value: "5"},
{ id: "50", name: "test50", value: "5"},
];
return mydata2;
};
</script>
<body>
<table id="grid"></table>
<script type="text/javascript">
jQuery("#grid").jqGrid({
data: dataset(),
colModel: [
{ name: "id", label:"ID"},
{ name: "name", label:"NAME", align: "center" },
{ name: "value", label:"VALUE", align: "center" }
],
cmTemplate: { editable: true, autoResizable: true },
}).jqGrid("navGrid", {refresh:true, edit:false, del:true, search:false, add:false})
.jqGrid("inlineNav", {save:true, edit:true, add:true})
</script>
</body></html>
If I correctly understand your problem then you want to reload the grid after saving. You can use jqGridInlineAfterSaveRow event for the purpose:
jQuery("#grid").on("jqGridInlineAfterSaveRow", function () {
setTimeout(function () {
jQuery("#grid").trigger("reloadGrid");
}, 0);
});

Get current data (object/json) from Bootstrap-Treeview

I am using Bootstrap-Treeview. I need a tree with checkboxes. And i want to send all tree to the server in treview format when button is pressed. But i can't understand how to extract actual data from treeview.
<html xmlns="http://www.w3.org/1999/html">
<head>
<link href="bootstrap-treeview.min.css" rel="stylesheet">
<link href="bootstrap.min.css" rel="stylesheet">
<script src="jquery.js"></script>
<script src="bootstrap-treeview.min.js"></script>
<script>
window.onload = function () {
var object = [
{
text: "Parent 1",
nodes: [
{
text: "Child 1",
nodes: [
{
text: "Grandchild 1"
},
]
},
{
text: "Child 2"
}
]
},
{
text: "Parent 2"
},
];
$('#tree').treeview({
data: object,
showCheckbox: true,
})
.on('nodeSelected', function (event, data) {
console.log('node selected = ' + JSON.stringify(event) + '; data = ' + JSON.stringify(data));
console.log('object =' + JSON.stringify(object));
console.log('tree =' + JSON.stringify($('#tree').data('treeview')));
console.log('tree 2 =' + JSON.stringify($('#tree')));
console.log('tree 3 =' + JSON.stringify($('#tree').treeview(true)));
});
};
</script>
</head>
<body>
<div id="tree">twetwe</div>
</body>
</html>
After page loads i check any checkbox and than click on any item, so console.log is called. But there is no info about actual state of all treeview. I need that information about all nodes :
{"text":"Child 2","nodeId":3,"parentId":0,"selectable":true,"state":{"checked":false,"disabled":false,"expanded":false,"selected":true}}
Its not possible to get all the nodes of the tree as such because no public method is available on the treeview object that would give the current state of the whole tree .i.e all the nodes.
However it is possible to extract that data indirectly say by combining outputs of treeview.getCollapsed() and treeview.getExpanded() methods into a single object.
<html xmlns="http://www.w3.org/1999/html">
<head>
<link href="bootstrap-treeview.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.1.0.min.js" integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s=" crossorigin="anonymous"></script>
<script src="bootstrap-treeview.min.js"></script>
<script>
window.onload = function () {
var object = [
{text: "Parent 1",
nodes: [{text: "Child 1",
nodes: [{text: "Grandchild 1"}]
},
{text: "Child 2"}
]
},
{text: "Parent 2"} ];
$('#tree').treeview({
data: object,
showCheckbox: true,
}).on('nodeSelected', function (event, data) {
console.log( getAllNodes() );
console.log( JSON.stringify(getAllNodes() ));
console.log('node selected = ' + JSON.stringify(event) + '; data = ' + JSON.stringify(data));
});
};
function getAllNodes(){
var treeViewObject = $('#tree').data('treeview'),
allCollapsedNodes = treeViewObject.getCollapsed(),
allExpandedNodes = treeViewObject.getExpanded(),
allNodes = allCollapsedNodes.concat(allExpandedNodes);
return allNodes;
}
</script>
</head>
<body>
<div id="tree">twetwe</div>`enter code here`
</body>
</html>
However please note that the resultant object is not similar in structure to input object that was supplied to treeview as data. Resultant object may be reformatted to construct an object similar to input object.

Binding and relationships in OpenUI5

Currently, I am trying to build an interface in OpenUI5, which is supposed to allow managing relationships. The whole application connects to the backend via oData.
Consider the following example: Two entities, "Group" and "Person". Each Group may consist of a number of Persons ("members"). What I'd like to do is to list all the Groups in a table - and for each groups members, I'd like to present a MultiComboBox to select the Persons associated with the group, like so:
Setting up the views is easy, but I have some trouble regarding the bindings. Binding a collection (like "Groups") to a table and binding properties (like "name") to an item is no problem of course, but I have no clue how to bind a collection - which is a child of another collection - to a nested list so to speak.
I don't even know if it is possible at all, especially since I want not only the Persons currently affiliated with a group to show up in the combo box, but all others as well to be able to select them. And of course, I want changes made in the interface to apply to the model as well...
Any hint towards a way to achieve the described functionality is much appreciated!
Two different models are binded to the Table..
YOu can have Groups and Members as entities with navigation property as members
you can play around here
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta http-equiv='Content-Type' content='text/html;charset=UTF-8'/>
<title>Mobile App in 23 Seconds Example</title>
<script src="https://sapui5.netweaver.ondemand.com/resources/sap-ui-core.js"
id="sap-ui-bootstrap"
data-sap-ui-libs="sap.m"
data-sap-ui-theme="sap_bluecrystal"></script>
<!-- only load the mobile lib "sap.m" and the Blue Crystal theme -->
<script type="text/javascript">
var sampleData = {
"Groups": [
{
"GroupId": "D1",
"GroupName": "Developers",
"Members": []
},
{
"GroupId": "D2",
"GroupName": "GreenDay",
"Members": []
},
{
"GroupId": "D3",
"GroupName": "BackStreet Boys",
"Members": []
},
{
"GroupId": "D4",
"GroupName": "Managers",
"Members": []
}
]
};
var oModel = new sap.ui.model.json.JSONModel(sampleData);
var aData = [
{
key: "A",
text: "John"
},
{
key: "B",
text: "Sachin"
},
{
key: "C",
text: "Dravid"
},
{
key: "D",
text: "David"
},
{
key: "E",
text: "Sunil"
},
{
key: "F",
text: "Ronald"
},
{
key: "G",
text: "Albert"
}
];
var oMulti = new sap.m.MultiComboBox({
selectionChange: function (oEvent) {
//change your group data?
}
});
oMulti.setModel(new sap.ui.model.json.JSONModel(aData));
var oTemplate = new sap.ui.core.Item({
key: "{key}",
text: "{text}",
customData: new sap.ui.core.CustomData({
key: "{GroupId}",
value: "{GroupName}"
})
});
oMulti.bindItems("/", oTemplate);
//Build Table
var oTable = new sap.m.Table({
columns: [
new sap.m.Column({
width: "150px",
header: new sap.m.Label({
text: "Group Name"
})
}),
new sap.m.Column({
header: new sap.m.Label({
text: "Members"
})
})
]
}).placeAt("content");
var oTemplate = new sap.m.ColumnListItem({
cells: [
new sap.m.Label({
text: "{GroupName}"
}),
oMulti
],
press: function (oEvent) {
alert(oEvent.getSource().getBindingContext());
}
});
oTable.setModel(oModel);
oTable.bindItems("/Groups", oTemplate);
</script>
</head>
<body class="sapUiBody">
<div id="content"></div>
</body>
</html>

Categories