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 1: Maciej Szakacz

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"}


Solution 2: ALEXANDER LOZANO

Convert using json encode

    import 'dart:convert';
    const JsonEncoder encoder = JsonEncoder.withIndent('  ');
    String myJSON =  '{codigo: 1050, decricao: Mage x, qntd: 1, tipo: UN, vUnit: 10,9, vTotal: 10,90}';
    String str = encoder.convert(myJSON);