5

My String

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

How change to :

{"id": "produk12549", "nama": "Abcd", "url": "myUrl"}
3
  • This has already been answered here: stackoverflow.com/a/64707588/17769156 Commented Feb 27, 2022 at 16:05
  • i try, but error like this : FormatException (FormatException: Unexpected character (at character 38) {"id": "produk12549", "nama": "ASOY" "ROYAL" "BIRU" "100gr" "TG" "pn", "url... Commented Feb 27, 2022 at 16:11
  • 1
    With which string did you try? Please share the code you're trying to execute, preferrably a snipet that will work in Dartpad so anyone can try it and fix it. Commented Feb 27, 2022 at 16:23

3 Answers 3

2
import 'dart:convert';

void main() {  
  Map<String, dynamic> result = jsonDecode("""{"id": "produk12549", "nama": "Abcd", "url": "myUrl"}""");
  print(result);
}
Sign up to request clarification or add additional context in comments.

1 Comment

I mean change this {id: produk12549, nama: Abcd, url: myUrl} to this {"id": "produk12549", "nama": "Abcd", "url": "myUrl"}
1

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

Comments

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

3 Comments

i need result like this {"id": "produk12549", "nama": "Abcd Bla Bla", "url": "myUrl"}
Bro, the output is a type: Map<String, String>, that is, keys and values are String type. Your question is about convert a value of String type into a value of Map<String,String> type. But if you need (which is really rare) to explicitly show the char " then use this line: .map((e) => MapEntry('"'+e.first+'"', '"'+e.last+'"'))
What if there array value like {urls:[one,two]} and what if the value contains two words separated by space like {name: "This is my name"}?. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.