问题
It's all in the title, I would like to generate a CSV file from the JSON objet get from this Ajax request,
The JSON I get represent all the recordings from a form :
I already have something that work for one field value a a single recording (the 0 here) :
<!DOCTYPE html>
<meta charset="utf-8"/>
<html>
<head>
<title>This is Website Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js" type="text/javascript"></script>
<script src="../FileSaver.js"></script>
<script>
var formId = 566091
// Définition des paramètres de la requête HTTP
var settings = {
"async": true,
"crossDomain": true,
"url": "https://www.kizeoforms.com/rest/v3/forms/"+formId+"/data/readnew",
"method": "GET",
"headers": {
"content-type": "application/json",
"Authorization": "******",
}
}
// Envoi de la requête et affichage en console de la réponse
$.ajax(settings).done(function (response) {
console.log(response);
var ssa3 = [];
for (var i = 0 ; i <= response.data.length; i++) {
ssa3.push(response.data[i].fields.ssa_3_a_22h00.value);
}
//var ssa3 = response.data[0].fields.ssa_3_a_22h00.value;
var blob = new Blob([ssa3], {type: "application/csv;charset=utf-8"});
saveAs(blob, "ssa3.csv");
});
</script>
</head>
</html>
I would now like to have this field value for all the recordings, I have tried to push it into a table but console tells me "i is undefined"
$.ajax(settings).done(function (response) {
console.log(response);
var ssa3 = [];
for (var i = 0 ; i <= response.data.length; i++) {
ssa3.push(response.data[i].fields.ssa_3_a_22h00.value);
}
var blob = new Blob([ssa3], {type: "application/csv;charset=utf-8"});
saveAs(blob, "ssa3.csv");
});
回答1:
Finally found it, I used a forEach to browse the data :
$.ajax(settings).done(function (response) {
console.log(response);
var ronde1n = [];
//on définit data qu'on va devoir parcourir avec un forEach
const data = response.data;
//on envoie les headers du fichiers csv
ronde1n.push("Numéro d'enregistrement,ID,Date et heure,conso SSA3");
//on parcours l'ensemble des enregistrements du formulaire Ronde 1 nuit
data.forEach(function (i) {
//on envoie les valeurs des champs qui nous intéressent pour chaque enregistrement
ronde1n.push("\r\n" + i.record_number + "," + i.id + "," + i.fields.date_et_heure.value + "," + i.fields.ssa_3_a_22h00.value);
});
//création du fichier CSV
var blob = new Blob([ronde1n], {type: "application/csv;charset=utf-8"});
saveAs(blob, "ronde1_nuit.csv");
});
来源:https://stackoverflow.com/questions/60171456/generate-a-csv-file-from-a-json-object