Home > database >  How to Convert String to json in Flutter
How to Convert String to json in Flutter

Time:02-28

My String

{id: produk12549, nama: Abcd, url: myUrl}

How change to :

{"id": "produk12549", "nama": "Abcd", "url": "myUrl"}

CodePudding user response:

You can use string manipulation to convert it to a valid json string and then encode for json. ie:

import 'dart:convert';
void main() {
  var s = "{id: produk12549, nama: Abcd, url: myUrl}";
  
  var kv = s.substring(0,s.length-1).substring(1).split(",");
  final Map<String, String> pairs = {};
  
  for (int i=0; i < kv.length;i  ){
    var thisKV = kv[i].split(":");
    pairs[thisKV[0]] =thisKV[1].trim();
  }
  
  var encoded = json.encode(pairs);
  print(encoded);
}

CodePudding user response:

void main(List<String> args) {
  const str = '{id: produk12549, nama: Abcd, url: myUrl}';
  var entries = str
    .substring(1,str.length-1)
    .split(RegExp(r',\s?'))
    .map((e) => e.split(RegExp(r':\s?')))
    .map((e) => MapEntry(e.first, e.last));
  var result = Map.fromEntries(entries);

  print(result);
}

Output:

{id: produk12549, nama: Abcd, url: myUrl}

CodePudding user response:

import 'dart:convert';

void main() {  
  Map<String, dynamic> result = jsonDecode("""{"id": "produk12549", "nama": "Abcd", "url": "myUrl"}""");
  print(result);
}
  • Related