user18223348
user18223348

Reputation:

How to Convert String to json in Flutter

My String

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

How change to :

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

Upvotes: 5

Views: 8488

Answers (3)

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}

Upvotes: 0

Cetin Basoz
Cetin Basoz

Reputation: 23867

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

Upvotes: 1

user18309290
user18309290

Reputation: 8380

import 'dart:convert';

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

Upvotes: 2

Related Questions