Convert string separated by comma to json

Asked

Viewed 175 times

0

I have the function:

$data ={
$G,3,"027",8,"sao paulo"
$H,3,"027",5,"curitiba"
$SP,3,"027",5,"brasilia",62312

}

          var dados = data.split(",");
          var json = [];
          var toSplit = dados.split(",");
          for (var i = 0; i < toSplit.length; i++) {
              json.push({
                      value : toSplit[0],
                      dados:[{
                        info: toSplit[i],
                      }]
             });
           }

The problem is that it does not return in the correct way, the expected would be:

{ "$G": { "0": 3, "1": "027", "2": 8, "3": "sao paulo"

}, "$H": { "0": 3, "1": "027", "2": 5, "3": "curitiba"

}, "$SP": { "0": 3, "1": "027", "2": 5, "3": "brasilia", "4": 62312 } }

I wish I knew where I was going wrong..

Tks

  • 2

    Hi! It is not clear where the string starts and ends... you can clarify where it comes from data? the {} are part of the string?

  • 1

    I believe that here dados.split(",") will make mistake for doing split in an array.

  • i receno line by line this way $G,3,"027",8,"sao paulo" /n $H,3,"027",5,"Curitiba" /n $SP,3,"027",5,"Brasilia",62312 /n

No answers

Browser other questions tagged

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