Can you pass content from a .txt file to JSON?

1

I have several .txt files equal to this content

Content:

0 69 164
0 71 117
0 73 84
0 79 80
0 82 83
0 82 115
0 83 154
0 84 48
1 69 104
1 71 100
1 73 83
1 79 82
1 82 121
1 83 117
1 84 46
2 69 204
2 71 94
2 73 85
2 79 102
2 82 88
2 82 147
2 83 87
2 84 42

I want to move it to JSON, with a column with different fields, following the format:

'[{"user":"0","tecla":"69","time":"164"}, ... ]'

Can you?

    
asked by hubman 17.10.2016 в 03:51
source

4 answers

3

using only fix arrangements:

if the text variable has that txt you can do this:

var arreglo = texto.split(/\r?\n/).map(function(linea){
    return linea.split(' ');
};
var arregloJson = JSON.stringify(arreglo);

That way arrangement is equal to:

[[0, 69, 164], [0, 71, 117], etc... ]

and arrayJson is equal to string JSONeado :

"[[0, 69, 164], [0, 71, 117], etc... ]"

using an object according to the second comment

var arreglo = texto.split(/\r?\n/).map(function(linea){
    var numeros = linea.split(' ');
    return {user: numeros[0], tecla: numeros[1], time: numeros[2]};
};
var arregloJson = JSON.stringify(arreglo);

notes:

  • The split(/\r?\n/) uses a regular expression that separates both Linux lines (separated by \n ) and Windows lines (separated by \r\n )
  • The proposed code can also be used on the client side in all current browsers.
  • answered by 17.10.2016 / 04:07
    source
    2

    NodeJS incorporates a módulo to read lines:

    const obj = {};
    const fs = require('fs');
    const lr = require('readline');
    
    console.log(obj.length);
    var lineReader = lr.createInterface({
      input: fs.createReadStream('dummy.txt')
    });
    
    lineReader.on('line', function (line) {
        let [ user, tecla, time ] = line.split(' ');
        obj[Object.keys(obj).length || 0] = { user, tecla, time };
    });
    
    lineReader.on('close', ()=>{
        fs.writeFile("dummy.txt", JSON.stringify(obj), function(err) {
            if(err) {
                return console.log(err);
            }
            console.log("Convertido a JSON");
        });
    
    });
    
        
    answered by 17.10.2016 в 04:21
    1

    This would be a way, having previously obtained the contents of the .txt and saving it in a string:

    var str = "0 69 164\n0 71 117\n0 73 84\n0 79 80\n0 82 83";
    var lines = str.split("\n");
    var data_json = [];
    var tmp;
    
    for(var index in lines){
    	tmp = lines[index].trim().split(" ");
    	data_json.push({
    		user : tmp[0],
    		tecla : tmp[1],
    		time : tmp[2]
    	});
    }
    console.log(data_json);
        
    answered by 17.10.2016 в 04:13
    1

    I create this function for a csv file, for a text file it will be the same ...

    function processFiles(files) {
        var file = files[0];
        var reader = new FileReader();
        reader.onload = function (e) {
            var output = document.getElementById("fileOutput");
            var texto = e.target.result;
            csvJSON(texto);
        };
        reader.readAsText(file);
    }
    
    function csvJSON(csv) {
        var lines = csv.split("\n");
        var result = [];
        var headers;
        for (var i = 0; i < lines.length; i++) {
            headers = lines[i].split("\n");
        }
        var cont = 0;
        for (var i = 0; i < lines.length; i++) {
    
            var obj = {};
            var currentline = lines[i].split("\n");
            for (var j = 0; j < headers.length; j++) {
                obj[cont] = currentline[j];
            }
            cont++;
            result.push(obj);
        }
    
        return JSON.stringify(result); //JSON
    
        
    answered by 17.10.2016 в 11:17