Lucas Barreto Luz
Lucas Barreto Luz

Reputation: 335

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?

Upvotes: 2

Views: 4270

Answers (3)

Tim
Tim

Reputation: 307

I adjusted Maciej Szakacz's answer to work for my use case, which is nested json. I'll provide the code below:

String jsonAddQuotes(String json){
  json = json.replaceAll('{', '{"');
  json = json.replaceAll(': ', '": "');
  json = json.replaceAll(', ', '", "');
  json = json.replaceAll('}', '"}');
  
  json = json.replaceAll('"{', '{');
  json = json.replaceAll('}"', '}');
  return json;
}

As commented on his answer, this won't work if you use : { } or , in your json values.

Upvotes: 0

ALEXANDER LOZANO
ALEXANDER LOZANO

Reputation: 2032

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

Upvotes: 2

Maciej Szakacz
Maciej Szakacz

Reputation: 614

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

Upvotes: 4

Related Questions