2

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 Answer 1

2

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}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.