Transform string into json

Asked

Viewed 374 times

0

I’m having a hard time converting string {data} in Json, I get her separated by comma several times, I’d like to turn her into 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 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,
   }
}
  • 1

    Your variable data in question is an array or a string?

  • is a string, I can create an array from it with split

  • If you can edit the question stating the return of this string data.

  • I didn’t understand the pq of having two variables with the same name!

  • I receive this string several times, that is, every second I have an update of it, so the example

3 answers

3


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

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]);

  • perfect!! Thanks so much for the help!!!!!

1

I believe that for this would have to occur some changes.

First his data would have to be an array with arrays and then you would need to create a function to convert your data in an object, always the first element being 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());

1

Sorry I can’t comment, so I’m going to release a new answer. Do not use the posted solution Array.prototype.toJson = function() {/*...*/}, this will create a property enumerated in all array type 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 various headaches, not to mention errors.

To add a new non-antaminable 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 safe way to add more methods to an object.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.