JSON to CSV with JavaScript. Sort column

Hello friends,

We are going to convert a Json file to Csv using JavaScript. We will show the result in a table with the TableView extension of @Ken

We will use the YouBee code in:
https://stackoverflow.com/questions/8847766/how-to-convert-json-to-csv-format-and-store-in-a-variable (with modifications)

p167Fi_javascript_json_csv.aia (22.2 KB)

<!DOCTYPE html>
<html><head><meta charset="utf-8"></head>
<body>
<p id="demo"></p>
<script>
var datos =  window.AppInventor.getWebViewString(); // Entrada de datos.

datos = JSON.stringify(datos);
datos = eval(datos);
datos = JSON.parse(datos);

JsonFields = ["id","Country","Populat.","Capital","Área"]; // Cabecera. Header.

function JsonToCSV(){
    var csvStr = JsonFields.join(",") + "\n";

    datos.forEach(element => {
        f1 = element.id;
        f2 = element.Country;
        f3 = element.Population;
        f4 = element.Capital;
		f5 = element.Area;
        csvStr +=  f1 + ',' + f2 + ','  + f3 + ',' + f4 + ',' + f5 + "\n"; })	
        return csvStr;
}

window.AppInventor.setWebViewString("" +JsonToCSV());  // Respuesta a CadenaDeWebView
//  document.getElementById("demo").innerHTML = JsonToCSV(); // Web
</script>
</body></html>

4 Likes

2.- Another example.

  • The files are in the same application as above.

  • Json file: usuarios.json

JavaScript code: usuarios.htm

<!DOCTYPE html>
<html><head><meta charset="utf-8"></head>
<body>
<p id="demo"></p>
<script>
var datos =  window.AppInventor.getWebViewString(); // Entrada de datos.

datos = JSON.stringify(datos);
datos = eval(datos);
datos = JSON.parse(datos);

JsonFields = ["id","Nombre","Edad","Nivel","Ciudad","Profesion"]; // Cabecera. Header.

function JsonToCSV(){
    var csvStr = JsonFields.join(",") + "\n";

    datos.forEach(element => {
        f1 = element.id;
        f2 = element.fields.Nombre;
        f3 = element.fields.Edad;
        f4 = element.fields.Nivel;
		f5 = element.fields.Ciudad;
		f6 = element.fields.Profesion;
        csvStr +=  f1 + ',' + f2 + ','  + f3 + ',' + f4 + ',' + f5  + ',' + f6 + "\n"; })	
        return csvStr;
}

window.AppInventor.setWebViewString("" +JsonToCSV());  // Respuesta a CadenaDeWebView
//  document.getElementById("demo").innerHTML = JsonToCSV(); // Web
</script>
</body></html>

Regards,
Juan A. Villalpando
http://kio4.com/appinventor/167F_javascript_json_csv.htm

3 Likes

3.- Sort column when you click on it.

p167Fi_javascript_json_csv_ordena.aia (22.6 KB)

  • Now when you click on a column it is ordered directly or inversely.
  • Restriction: numbers without decimal separator.

ordena.htm

<!DOCTYPE html>
<html>
<head><meta charset="utf-8"></head><body>
<p id="demo"></p>
<script>
var data =  window.AppInventor.getWebViewString(); // Entrada de datos.

    parte = data.split("|"); 
    ordena = parte[0]; // sort this column
	reverse = parte[1]; // reverse (1 or -1)
    datos = parte[2];   // datos

datos = JSON.stringify(datos);
datos = eval(datos);
datos = JSON.parse(datos);

//////////////////////////////////// Ordena columnas de numeros. Numbers.
const sort_by2 = (field, reverse, primer) => {
  const key = primer ?
    function(x) {
      return primer(x[field])
    } :
    function(x) {
      return x[field]
    };

  // reverse = !reverse ? 1 : -1;

  return function(a, b) {
    return a = key(a), b = key(b), reverse * ((a > b) - (b > a));
  }
}
///////////////////////////////// Ordena columnas de cadenas. Strings.
var sort_by = function() {
    var fields = [].slice.call(arguments),
       n_fields = fields.length;

    return function(A, B) {
		var a, b, field, key, primer, result;
        for (var i = 0, l = n_fields; i < l; i++) {
            result = 0;
            field = fields[i];

            key = typeof field === 'string' ? field : field.name;

            a = A[key];
            b = B[key];

            if (typeof field.primer !== 'undefined') {
                a = field.primer(a);
                b = field.primer(b);
            }

          //  reverse = (field.reverse) ? -1 : 1;

            if (a < b) result = reverse * -1;
            if (a > b) result = reverse * 1;
            if (result !== 0) break;
        }
        return result;
    }
}

JsonFields = ["id","Country","Populat.","Capital","Área"]; // Cabecera. Header.
Columnas_ordenar = ["id","Country","Population","Capital","Area"]; // Ordenar una.
var ordena_esta = Columnas_ordenar[ordena];

if (ordena == 2 || ordena == 4) { // Columnas numéricas 2 and 4. Columns with numbers.
datos.sort(sort_by2(ordena_esta, reverse, parseInt)); // Numeros
} else {
datos.sort(sort_by(ordena_esta, {name: ordena_esta,primer: parseInt,reverse: reverse})); // Cadenas
}

////////////// Presentacion en csv //////////////////////////////////
function JsonToCSV(){
    var csvStr = JsonFields.join(",") + "\n";

    datos.forEach(element => {
        f1 = element.id;
        f2 = element.Country;
        f3 = element.Population;
        f4 = element.Capital;
		f5 = element.Area;
        csvStr +=  f1 + ',' + f2 + ','  + f3 + ',' + f4 + ',' + f5 + "\n"; })	
        return csvStr;
}

window.AppInventor.setWebViewString("" +JsonToCSV());  // Respuesta a CadenaDeWebView
//  document.getElementById("demo").innerHTML = JsonToCSV(); // Web
</script>
</body></html>

Base code with modifications:

3 Likes