Convert JavaScript String to Map Flutter

Viewed 90

I have a string like this:

'var key1 = "abcd"; var key2 ="xyz";'

and I want to convert this into the map or JSON, in Dart, like this:

{
'key1': 'abcd',
'key2': 'xyz'
}

Is there a way I can convert the J/S file as a string to a Dart map?

1 Answers

To generate a Map form your string. You can use the help of regular expressions (online demo).

The following code captures two groups that are within the () and creates a Map out of them:

void main() {
  final s = 'var key1 = "abcd"; var key2 ="xyz"';
  
  final reg = RegExp(r'var (.*?)=\s?"(.*?)"');
  final myMap = Map.fromEntries(
      reg.allMatches(s).map((m) => MapEntry(m.group(1), m.group(2))));
  print(myMap);
}

Output:

{key1 : abcd, key2 : xyz}
Related