Search code examples
jsonflutterdarttostring

Dart convert string without quotes to json


I am trying to convert a string to json string.

String I get:

String myJSON =  '{codigo: 1050, decricao: Mage x, qntd: 1, tipo: UN, vUnit: 10,9, vTotal: 10,90}';

String I need:

String myJSON =  '{"codigo": "1050", "decricao": "Mage x", "qntd": "1", "tipo": "UN", "vUnit": "10,9", "vTotal": "10,90"}';

Could someone shed some light on how I can add the quotes?


Solution

  • You can easily convert a String using replaceAll.

    Code:

      String myJSON =  '{codigo: 1050, decricao: Mage x, qntd: 1, tipo: UN, vUnit: 10,9, vTotal: 10,90}';
      myJSON = myJSON.replaceAll('{', '{"');
      myJSON = myJSON.replaceAll(': ', '": "');
      myJSON = myJSON.replaceAll(', ', '", "');
      myJSON = myJSON.replaceAll('}', '"}');
      print(myJSON);
    

    Output:

    {"codigo": "1050", "decricao": "Mage x", "qntd": "1", "tipo": "UN", "vUnit": "10,9", "vTotal": "10,90"}