Can a TXT file be converted to JSON ?? Some example of JavaScript function. I'm a noob

0

I currently have this format of txt

RODRIGUEZ=Apellido Paterno ,ESQUIVEL= Apellido Materno  ,HECTOR 
MIGUEL=Nombres  ,C RAYON 41=Direccion 

And I want to change it to JSON format so that it becomes more readable. I would appreciate any help

I have this function where archivo.txt is the file that I generate and I want to pass it to json. I'm not sure if that works.

var file_name = 'archivo.txt';

var readline = require('readline');
var fs = require('fs');

var lineReader = readline.createInterface({
    input: fs.createReadStream(file_name)
});

var isHeader = false;
var columnNames = [];

function parseLine(line) {
    return line.trim().split('\t')
}

function createRowObject(values) {
    var rowObject = {};

    columnNames.forEach((value,index) => {
        rowObject[value] = values[index];
    });

    return rowObject;
}

var json = {};
json[file_name] = [];

lineReader.on('line', function (line) {
    if(!isHeader) {
        columnNames = parseLine(line);
        isHeader = true;
    } else {
        json[file_name].push(createRowObject(parseLine(line)));
    }
});

lineReader.on('close', function () {
    fs.writeFileSync(file_name + '.json', JSON.stringify(json,null,2));
});
//Termina
    
asked by Noé Torres 10.08.2018 в 03:23
source

2 answers

1

I admit that I made a bit of trouble for the resolution, but an alterative could be something like this:

<html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    </head>
    <body>
        <input type='file' accept='text/plain' onchange='openFile(event)'>
    </body> 
</html>
<script type="text/javascript">
var openFile = function(event) 
{
    var input = event.target;
    var reader = new FileReader();
    reader.onload = function()
    {
        var texto = reader.result;
        var texto_array = texto.split("\r\n");
        var nombre;
        var apellido;
        var edad;
        var i = 0;
        for (var element in texto_array) 
        {
            var json_element;
            if(i%3 == 0)
                nombre = texto_array[element];
            else if(i%3 == 1)
                apellido = texto_array[element];
            else if(i%3 == 2)
            {
                edad = texto_array[element];
                json_element = {"nombre": nombre, "apellido": apellido, "edad": edad};
                console.log(json_element);
            }
            i++;
        }
    };
    reader.readAsText(input.files[0]);
}
</script>

Exit:

Text Reading Font

In your case you should adapt the split and the i% number to opt for this solution. Greetings.

    
answered by 10.08.2018 в 05:07
0

I solved it this way .. I already tried it and it's working ..

<html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    </head>
    <body>
        <input type='file' accept='text/plain' onchange='openFile(event)'>
    </body> 
</html>
<script type="text/javascript">

function escapeSpecialChars(jsonString) {
    return jsonString.replace(/\n/g, "\n")
    .replace(/\r/g, "\r")
    .replace(/\t/g, "\t")
    .replace(/\f/g, "\f");
}

var openFile = function(event) 
{
    var input = event.target;
    var reader = new FileReader();
    reader.onload = function()
    {
        var texto = reader.result.replace(new RegExp(',$'), '');
        var texto_array = texto.split(",");

        let elementoSoloValue = null; 
        let jsonINE = "["; 
        texto_array.forEach(function(datoINE, indexElement){ 
            let keyValue = datoINE.split('='); 

            if(keyValue.length > 1){


                if(elementoSoloValue){
                    keyValue[0] = elementoSoloValue + " " + keyValue[0];
                    elementoSoloValue = null; // Reseteamos a null de que ya no hay elemento solo por ahora
                }


                jsonINE +='{' +
                    '"name": "' + keyValue[1] + '", ' +
                    '"value": "' + keyValue[0] + '", ' +
                    '"sinEspaco": "' + (keyValue[1]).replace(new RegExp(' ', 'g'), '') + '"' +
                '}';

                // Si no es el último elemento del arreglo texto_array, le agregamos una coma al string, porque se va a agregar otro elemento,
                // Pero si es esl último ya no le pongamos coma
                if(indexElement + 1 < texto_array.length){
                    jsonINE += ',';
                }
            }else{

                elementoSoloValue = keyValue[0];
            }
        });
        jsonINE += ']'; //Cerramos el arreglo

        jsonINE = escapeSpecialChars(jsonINE); // Escapamos los caracteres especiales
        var ine = JSON.parse(jsonINE); // Convertimos el string a JSON
        console.log('INE EN FORMATO JSON:');
        console.log(ine);


    };
    reader.readAsText(input.files[0]);
}
</script>
    
answered by 10.08.2018 в 22:50