List on json file - javascript

I have a problem with the list on json file data.
i want to catch the informations from json file and insert these in list.
HTML :
<ol id="dataT">
</ol>
JavaScript :
function GetData(index) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
ShowJson(this.responseText);
}
};
var counter;
switch (index) {
case "1":
counter = "./data/data1.json";
break;
case "2":
counter = "./data/data2.json";
break;
case "3":
counter = "./data/data3.json";
break;
default:
counter = "./data/data1.json";
}
xhttp.open("GET", counter, true);
xhttp.send();
}
function ShowJson(JsonData) {
var obj = JSON.parse(JsonData);
document.getElementById("dataT").innerHTML = obj.dataT;
}
Json file data:
"dataT" : {"tag":"ol","children":[
{"tag":"li","html":"Please Love Me"},
{"tag":"li","html":"You Upset Me Baby"},
{"tag":"li","html":"Everyday I Have The Blues"},
{"tag":"li","html":"Bad Luck"},
{"tag":"li","html":"3 O'Clock Blues"},
{"tag":"li","html":"Blind Love"},
{"tag":"li","html":"Woke Up This Morning"},
{"tag":"li","html":"You Know I Love You"},
{"tag":"li","html":"Sweet Little Angel"},
{"tag":"li","html":"Ten Long Years"},
{"tag":"li","html":"Did You Ever Love A Woman"},
{"tag":"li","html":"Crying Won't Help You"}
]}
In this moment, the result is : [object Object].

You can't directly assign data to innerHTML like 'document.getElementById("dataT").innerHTML = obj.dataT;' as you have done in your code.
You have to iterate through your data obj to bind list items one by one like:
function bindData() {
var myData = {
"dataT": {
"tag": "ol",
"children": [{
"tag": "li",
"html": "Please Love Me"
},
{
"tag": "li",
"html": "You Upset Me Baby"
},
{
"tag": "li",
"html": "Everyday I Have The Blues"
},
{
"tag": "li",
"html": "Bad Luck"
},
{
"tag": "li",
"html": "3 O'Clock Blues"
},
{
"tag": "li",
"html": "Blind Love"
},
{
"tag": "li",
"html": "Woke Up This Morning"
},
{
"tag": "li",
"html": "You Know I Love You"
},
{
"tag": "li",
"html": "Sweet Little Angel"
},
{
"tag": "li",
"html": "Ten Long Years"
},
{
"tag": "li",
"html": "Did You Ever Love A Woman"
},
{
"tag": "li",
"html": "Crying Won't Help You"
}
]
}
};
for (var i in myData.dataT.children) {
var node = document.createElement("LI");
var textnode = document.createTextNode(myData.dataT.children[i].html);
node.appendChild(textnode);
document.getElementById("dataT").appendChild(node);
}
}
<ol id="dataT"></ol>
<button onclick="bindData()">Bind Data</button>

Related

Html generator from json appendchild to the wrong parent

I am coming to you today,
I tried to make an html generator from a json file in javascript.
The problem being that arrived at a certain moment the children "appendChild" to the previous element instead of "appendChild" to the parent
here is my code :
$(document).ready(function(){
$.getJSON('THE JSON FILE FROM URL', function(data){
const components = data.htmlComponents.tableSuiviCommandes.components;
createHtmlFromJson(components)
}).fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err );
});
function createHtmlFromJson(json, parent){
json.forEach(jsonElement => {
// log("jsonElemement", jsonElement)
createdElement = document.createElement(jsonElement.balise);
if(jsonElement.content) createdElement.innerHTML = jsonElement.content;
jsonElement.attributes?.forEach(element => {
createdElement.setAttribute(element.name, element.content);
});
if(!parent){
document.body.appendChild(createdElement);
}else {
parent.appendChild(createdElement);
}
jsonElement.childs?.forEach(element => {
let theParent = createdElement;
if(element != typeof Array) element = [element];
createHtmlFromJson(element, theParent);
});
});
}
function log(name, value){
console.log("----------");
console.log(name);
console.log(value);
console.log("----------")
}
});
the json file :
{
"htmlComponents": {
"tableSuiviCommandes": {
"components": [
{
"balise": "div",
"attributes": [
{
"name": "class",
"content": "containerTable"
}
],
"childs": [
{
"balise": "table",
"childs": [
{
"balise": "thead",
"childs": [
{
"balise": "tr",
"childs": [
{
"balise": "th",
"content": "Id"
},
{
"balise": "th",
"content": "Statut"
},
{
"balise": "th",
"content": "Voir la demande"
},
{
"balise": "th",
"content": "Objet"
},
{
"balise": "th",
"content": "Projet/Application"
},
{
"balise": "th",
"content": "Demandeur(s)"
},
{
"balise": "th",
"content": "Site"
},
{
"balise": "th",
"content": "Expression de besoin"
},
{
"balise": "th",
"content": "Référence interne"
},
{
"balise": "th",
"content": "CDC retenu"
},
{
"balise": "th",
"content": "N°Cotation"
},
{
"balise": "th",
"content": "N°Devis"
},
{
"balise": "th",
"content": "Date devis"
},
{
"balise": "th",
"content": "N°DEMAP"
},
{
"balise": "th",
"content": "N°CMD"
},
{
"balise": "th",
"content": "N°GAFI"
},
{
"balise": "th",
"content": "Date prévisionnelle de livraison"
},
{
"balise": "th",
"content": "Date de livraison"
},
{
"balise": "th",
"content": "Commentaire"
}
]
}
]
},
{
"balise": "tbody",
"attributes": [
{
"name": "id",
"content": "tableauSuivi"
}
]
}
]
}
]
}
]
}
}
}
the html generate :
I tried with the debbuger to make step by step, but I really don't understand why theParent is not really the parent so that the children are children of the previous element
// You try this code
$(document).ready(function () {
createHtmlFromJson(JSON.parse(json).htmlComponents.tableSuiviCommandes.components)
function createHtmlFromJson(json, parent) {
// console.log(json);
json.forEach(jsonElement => {
// log("jsonElemement", jsonElement)
createdElement = document.createElement(jsonElement.balise);
if (jsonElement.content) createdElement.innerHTML = jsonElement.content;
jsonElement.attributes?.forEach(element => {
createdElement.setAttribute(element.name, element.content);
});
if (!parent) {
document.body.appendChild(createdElement);
} else {
parent.appendChild(createdElement);
}
let theParent = createdElement;
jsonElement.childs?.forEach(element => {
// console.log(createdElement);
if (element != typeof Array) element = [element];
// console.log(theParent);
createHtmlFromJson(element, theParent);
});
});
}
});
I'd suggest extracting a logic of creating a single HTML element into separate function. It may simplify things in terms of understanding. Here is a createElement function based on your createHtmlFromJson function, but it creates only single element (and all of its children of course) and just returns it:
function createElement(component) {
const el = document.createElement(component.balise);
if (component.content) {
const text = document.createTextNode(component.content);
el.appendChild(text);
}
component.attributes?.forEach((attr) => {
el.setAttribute(attr.name, attr.content);
});
component.childs?.forEach((child) => {
// Create all of its children and append them to this element
el.appendChild(createElement(child));
});
return el;
}
Now you can create an array of HTML elements based on your JSON, like so:
const { components } = data.htmlComponents.tableSuiviCommandes;
// Transform each object into the actual HTML element via `.map()`
const arrayOfHTMLElements = components.map(createElement);
And then you can append it to the DOM, like so:
arrayOfHTMLElements.forEach((element) => {
document.body.appendChild(element);
});

Trying to see if I can run the same Slack message payload multiple times in Google scripts via data from a spreed sheet

I have a spreadsheet of data where I pull data from an array of data. After I declare the data, I run the code and it sends a message to slack using their block kit.
Issue is I have to manually input what values of the data should be. I was wondering if there is a way to pull data for my message payload>post it to the channel>then repeat this process till no more data is left.
Example Spreadsheet will look like this below:
Greeting
Word
Holla
Mundo
Hello
World
Right now to pull my row and send a message I have it set up like this;
function main() {
// Grabbing data from Google Sheet
data = getGoogleSheetData(SHEET_ID)
Logger.log(data)
//Variables for data
Data1 = data[0][0]
Data2 = data[0][2]
However I have to always change the first array to match up with the next line of data,
Then run it.
So if I want to send my message once more I just change the values to this then run it.
//Variables for data
Data1 = data[1][0]
Data2 = data[1][2]
Hopefully that makes sense. Any guidance is of course much appreciated
Edit***
Here is the code example:
// Method use to post in Slack channel
function sendAlert(payload) {
const webhook = SLACK_URL; //Paste your webhook URL here
var options = {
"method": "post",
"contentType": "application/json",
"muteHttpExceptions": true,
"payload": JSON.stringify(payload)
};
try {
UrlFetchApp.fetch(webhook, options);
} catch(e) {
Logger.log(e);
}
}
// Defining the data range and vaules to grab from a Google Sheet
function getGoogleSheetData(GoogleSheetId) {
sheet_data = SpreadsheetApp.openById(GoogleSheetId)
let data = sheet_data.getSheetByName('sheet1').getRange("A1:AP17").getValues();
return data
}
function main() {
// Grabbing data from Google Sheet
data = getGoogleSheetData(SHEET_ID)
Logger.log(data)
//Variables for data
Date = data[0][0]
Contact_ID = data[0][2]
Sources = data[0][9]
Offer = data[0][10]
Accepted_Declined = data[0][12]
Recruiter = data[0][19]
Posting_Title = data[0][18]
Question_1 = data[0][33]
Question_2 = data[0][34]
Question_3 = data[0][35]
Question_4 = data[0][36]
Question_5 = data[0][37]
Question_6 = data[0][38]
Question_7 = data[0][39]
Question_8 = data[0][40]
Question_9 = data[0][41]
// check to see if Question_1 is null
if(Question_1.length != 0){
Logger.log(data);
} else
{
Question_1 = "N/A"
}
// Check if Question_2 is null
if(Question_2.length != 0) {
Logger.log(data);
} else
{
Question_2 = "N/A"
}
// Check if Question_3 is null
if(Question_3.length != 0){
Logger.log(data);
} else
{
Question_3 = "N/A"
}
// Check if Question_4 is null
if(Question_4.length != 0){
Logger.log(data);
} else
{
Question_4 = "N/A"
}
// Check if Question_5 is null
if(Question_5.length != 0){
Logger.log(data);
} else
{
Question_5 = "N/A"
}
// Check if Question_6 is null
if(Question_6.length != 0){
Logger.log(data);
} else
{
Question_6 = "N/A"
}
// Check if Question_7 is null
if(Question_7.length != 0){
Logger.log(data);
} else
{
Question_7 = "N/A"
}
// Check if Question_8 is null
if(Question_8.length != 0){
Logger.log(data);
} else
{
Question_8 = "N/A"
}
// Check if Question_9 is null
if(Question_9.length != 0){
Logger.log(data);
} else
{
Question_9 = "N/A"
}
message_payload = {
"blocks": [
{
"type": "header",
"text": {
"type": "plain_text",
"text": "Candidate Experience Survey Responses :lever:",
"emoji": true
}
},
{
"type": "divider"
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*Date Applied*\n" + String(Date),
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*ID*\n" + String(Contact_ID)
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*Source*\n" + String(Sources)
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*Offer*\n" + String(Offer)
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*Current Status*\n" + String(Accepted_Declined)
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*Recruiter*\n" + String(Recruiter)
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*Posting Title*\n" + String(Posting_Title)
}
},
{
"type": "section",
"fields": [
{
"type": "mrkdwn",
"text": "*question 1*\n" + String(Question_1)
},
{
"type": "mrkdwn",
"text": "*question 2*\n" + String(Question_2)
},
{
"type": "mrkdwn",
"text": "question 3*\n" + String(Question_3)
},
{
"type": "mrkdwn",
"text": "*question 4*\n" + String(Question_4)
},
{
"type": "mrkdwn",
"text": "Question 5\n" + String(Question_5)
},
{
"type": "mrkdwn",
"text": "Question 6\n" + String(Question_6)
},
{
"type": "mrkdwn",
"text": "Question 7*\n" + String(Question_7)
},
{
"type": "mrkdwn",
"text": "Question 8\n" + String(Question_8)
},
{
"type": "mrkdwn",
"text": "Question 9\n" + String(Question_9)
}
]
}
]
}
test = sendAlert(message_payload)
Logger.log(test)
Logger.log(test)
The Spread Sheet looks like has the data in each line.
Right now I change the data manually in my code.
So I ran the code first for the arrays of data [0][0] and so on then change it to [1][0] and so on till I am out of data in spreadsheet.
Looking to find a way of doing that automatically in the code instead of me manually changing the values then running it.
Hopefully that explains it better.

Looping over JSON nested array in JavaScript

I have an API which give me a JSON file like this :
(I edited my post.i hope it can help)
{
"events": {
"Israel Liga Bet South": [
{
"id": 47,
"league_name": "Israel Liga Bet South",
"home_team": "Otzma FC Holon",
"away_team": "Beitar Ramat Gan"
}
],
"Israel Liga Bet North": [
{
"id": 46,
"league_name": "Israel Liga Bet North",
"home_team": "Bnei HaGolan VeHaGalil",
"away_team": "Maccabi Maalot Tarshiha"
}
],
"India Bangalore Super Division": [
{
"id": 40,
"league_name": "India Bangalore Super Division",
"home_team": "ASC",
"away_team": "South United"
}
]
}
}
i wrote this code :
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
var events;
events = myObj.events;
Object.keys(events).forEach(function (key) {
var inPlayEvents = events[key];
inPlayEvents.forEach(element => {
var div = document.createElement('div');
div.innerHTML = "my html codes";
div.setAttribute('class', 'event-type');
document.body.appendChild(div);
});
});
}
};
xmlhttp.open("GET", "json.txt", true);
xmlhttp.send();
but it showing me all of the matches
I want to show the same league matches in the same <div>
how can I do it?
thanks for your help
First, your JSON is wrongly formatted and it wouldn't even parse. Assuming the JSON object is like this:
"Categories": {
"cat1": [
{
"id": 1,
"Category_name": "cat1",
"Name": "iphone6",
"Details": "packed",
}
],
"cat2": [
{
"id": 2,
"Category_name": "cat2",
"Name": "GalaxyS10",
"Details": "stock"
}
],
"cat1": [
{
"id": 3,
"Category_name": "cat1",
"Name": "iphone5s",
"Details": "stock"
}
]
}
As for but it showing me all of the products I want to show the same category products in the same div you need to change the following in your iterator code:
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
var Categories;
Categories = myObj.Categories;
Object.keys(Categories).forEach(function(key) {
var Products = Categories[key];
// create your div here
var div = document.createElement('div');
div.innerHTML = '';
Products.forEach(element => {
//[! remove this] var div = document.createElement('div');
//[! concatenate instead of assigning it] div.innerHTML = "html codes here";
div.innerHTML += 'your html here';
div.setAttribute('class', 'category-type');
Why? Because in your code you are reassigning the HTML to a new div for every product. Since you want to display all the information for all products under each category in a single div, your code would not work as expected.

Parse HTML into a specific JSON object

How can I create a specific JSON object from some HTML?
Example
This is very well formatted HTML page (rendered from markdown). I want to create a JSON representation of the sections on the page.
So each "h2" is a title. Each h3, h4, or h5, that follows it is a subtitle
Given this HTML:
<h2>Charts</h2>
<ul>...</ul>
<h5>Third Party</h5>
<ul>...</ul>
<h5>Reusable Chart Frameworks</h5>
<ul>...</ul>
<h2>Maps</h2>
<h5><a href="#third-party-1">Third Party</h5>
...
Return this JSON:
[
{
"title": {
"text": "Charts",
"href": "#charts"
}
"subtitles": [
{
"text": "Third Party",
"href": "#third-party"
},
{
"text": "Reusable Chart Frameworks",
"href": "#reusable-chart-frameworks"
}
]
},
{
"title": {
"text": "Maps",
"href": "#maps"
},
"subtitles": ]
"text": "Third Party",
"href": "#third-party-1"
]
},
...
]
Solutions I've considered
Seems like something jQuery could help a lot with. If the items were nested it would be very easy to do $('h2').each(...) and just loop through each section, appending it to my JSON object. However there is no nesting here, just siblings. Any ideas?
One other solution is to map it:
var mappedJSON = $('h2').map(function() {
var $selfA = $(this).children('a');
var subtiles = $(this).nextUntil('h2').filter(':header').children('a').map(function() {
return {
"text": $(this).text(),
"href": $(this).attr('href')
}
}).get();
return {
"title": {
"text": $selfA.text(),
"href": $selfA.attr('href')
},
"subtitles": subtiles
};
}).get();
console.log(mappedJSON);
$('<pre/>').appendTo($('body').empty()).text(JSON.stringify(mappedJSON, null, "\t"));
pre {
tab-size: 2;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h2>Charts</h2>
<ul>...</ul>
<h5>Third Party</h5>
<ul>...</ul>
<h5>Reusable Chart Frameworks</h5>
<ul>...</ul>
<h2>Maps</h2>
<h5><a href="#third-party-1">Third Party</h5>
Here's a solution that just relies on jQuery's .nextUntil() function.
var sections = [];
var eTitles = $('article').find('h2');
$(eTitles).each(function(){
var section = {
"title": {
"text": $(this).text(),
"href": $(this).find('a').attr('href')
},
"subtitles": []
}
var eSubtitles = $(this).nextUntil('h2').filter('h3, h4, h5');
$(eSubtitles).each(function(){
var subtitle = {
"text": $(this).text(),
"href": $(this).find('a').attr('href')
}
section.subtitles.push(subtitle);
});
sections.push(section);
});

how to create elements dynamically in HTML using JSON file

I want to create HTML elements dynamically using JSON file.
{"myObject": {
"JAVA": {
"id": "JAVAsubj",
"path": "json/data.json"
},
"C#": {
"id": "JAVAsubj",
"path": "json/data1.json"
},
"C++": {
"id": "JAVAsubj",
"path": "json/data2.json"
}
}
}
This is my JSON file. i want to create HTML buttons dynamically. Buttons should be create like JAVA,C#,C++. if i add something next to C++ then that button should get created dynamically
You can try something like this FIDDLE
however, i changed the myObject to an array of json objects as follows:
var jsonObj = {"myObject":
[
{
title: 'JAVA',
id: "JAVAsubj",
path: "json/data.json"
},
{
title: "C#",
id: "JAVAsubj",
path: "json/data1.json"
},
{
title: "C++",
id: "JAVAsubj",
path: "json/data2.json"
}
]
}
var count = Object.keys(jsonObj.myObject).length;
var container= document.getElementById('buttons'); // reference to containing elm
for(var i=0;i<count;i++){
var obj= jsonObj.myObject[i];
var button = "<input type='button' value="+obj.title+"></input>"
container.innerHTML+=button;
}
First thing you need to do that get your JSON into js object :
var myJSON= {"myObject": {
"JAVA": {
"id": "JAVAsubj",
"path": "json/data.json"
},
"C#": {
"id": "JAVAsubj",
"path": "json/data1.json"
},
"C++": {
"id": "JAVAsubj",
"path": "json/data2.json"
}
}
}
now get the value of your object into dictionary like below :
var dctLanguages = myJSON["myObject"];
now to render buttons dynamically, just do this :
var strHTML = '';
for (var key in dctLanguages)
{
var language = dctLanguages[key];
strHTML += '<input type="button" id="'+language.id+'" value="'+key+'"/>';
}
and append this HTML into your container div as follows :
$(strHTML).appendTo("#container");
Hope this will work for you..
const info = [
{
"id": 1,
"img": "a.jpg",
"name": "Avinash Mehta",
"desc": "I am Web Developer"
},
{
"id": 2,
"img": "c.jpg",
"name": "Avinash",
"desc": "I am Web"
},
{
"id": 3,
"img": "b.jpg",
"name": "Mehta",
"desc": "I am Developer"
},
]
const main = document.querySelector(".main");
window.addEventListener("DOMContentLoaded", function(){
let displayInfo = info.map(function(profile){
return` <div class="profile">
<img src="${profile.img}" alt="">
<h2>${profile.name}</h2>
<p>${profile.desc}</p>
</div>`
});
displayInfo = displayInfo.join("");
main.innerHTML = displayInfo
})
This shoule help you
const info = [
{
"id": 1,
"img": "a.jpg",
"name": "Avinash Mehta",
"desc": "I am Web Developer"
},
{
"id": 2,
"img": "c.jpg",
"name": "Avinash",
"desc": "I am Web"
},
{
"id": 3,
"img": "b.jpg",
"name": "Mehta",
"desc": "I am Developer"
},
]
const main = document.querySelector(".main");
window.addEventListener("DOMContentLoaded", function(){
let displayInfo = info.map(function(profile){
return` <div class="profile">
<img src="${profile.img}" alt="">
<h2>${profile.name}</h2>
<p>${profile.desc}</p>
</div>`
});
displayInfo = displayInfo.join("");
main.innerHTML = displayInfo
})

Categories

Resources