Transform string into json

0

I'm having trouble converting string {data} to Json , I get it separated by commas several times, I would like to convert it to Json to collect the first key

var data = [ "$SP", "92", "00:01:36.340", "00:05:48.929\n" ];
var data = [ "$MT", "91", "00:00:34.187", "00:18:44.001\n" ];

the desired one would be:

{  
   "$SP":{  
      "0":92,
      "1":"00:01:36.340",
      "2":"00:05:48.929",
   }
},
{
   "$MT":{  
      "0":91,
      "1":"00:00:34.187",
      "2":00:18:44.001,
   }
}
    
asked by anonymous 31.10.2018 / 18:14

3 answers

3

Using for...in you can mount this JSON as you have spoken. Create a function and each time you receive the array data throw it to the function that will add new entries to a pre-created object (ex, var json = {} ). See:

var json = {}; // crio o objeto principal

function addJson(data){
   var chave; // declaro a variável que será o nome do sub-objeto
   for(var i in data){
      if(i == 0){ // trata apenas o primeiro valor da array, que será o nome do sub-objeto
         chave = data[i]; // declaro a variável com o primeiro valor da array
         json[chave] = {}; // cria o objeto com o primeiro valor da array
      }else{
         json[chave][i-1] = data[i]; // adiciona as entradas seguindo a ordem dos índices a partir de 0
      }
   }
}

// primeiro array recebido para adicionar ao objeto "json"
var data = [ "$SP", "92", "00:01:36.340", "00:05:48.929\n" ];
addJson(data); // envia para a função

// segundo array recebido para adicionar ao objeto "json"
data = [ "$MT", "91", "00:00:34.187", "00:18:44.001\n" ];
addJson(data); // envia para a função

console.log(json);
console.log(json.$MT[0]);
    
31.10.2018 / 20:38
1

I believe that some changes would have to take place.

First of all your data would have to be an array with arrays and then you would need to create a function to convert your data to an object, always the first element would be the key.

I made a quick code here, see if you understand:

var data = [
    [ "$SP", "92", "00:01:36.340", "00:05:48.929" ], 
    [ "$MT", "91", "00:00:34.187", "00:18:44.001" ]
];

Array.prototype.toJson = function() {
	var obj = {};
    
    for(var i = 0; i < this.length; i++) {
    	var key = this[i].shift();
    	obj[key] = this[i]; 
    }
    
    return obj;
};

console.log(data.toJson());
    
31.10.2018 / 18:33
1

Sorry, you can not comment, so I'll post a new reply. Do not use the posted solution Array.prototype.toJson = function() {/*...*/} , this will create an enumerated property on all array objects. See the example:

Array.prototype.toJson = function() {
    var obj = {};    
    for(var i = 0; i < this.length; i++) {
        var key = this[i].shift();
        obj[key] = this[i]; 
    }    
    return obj;
}

var arr = [0, 1, 2, 3, 4];
for (var key in arr) {
    console.log(key);
}

Now every time you iterate over the indices of an array, you will get toJson, which can cause you several headaches, not to mention errors.

To add a new non-enumerable method to your arrays, use this statement:

Object.defineProperty(Array.prototype, 'toJson', {
    value: function (property, value) {
      let obj = {};
      for(let i = 0; i < this.length; i++) {
        obj[this[i].shift()] = this[i]; 
      }
      return obj;
    }
});

var arr = [0, 1, 2, 3, 4];
for (var key in arr) {
    console.log(key);
}

Note that toJson no longer appears as a property of your array, this is the sure way to add more methods to an object.

    
31.10.2018 / 19:03