Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart: Convert String representation of List of Lists to List of List

Tags:

dart

this is the same question as here:

How can I convert this string to list of lists?

but for Dart rather than python. My aim (as in the other question) is to take a string like:

String stringRep = '[[123],[122],[411]]';

And convert it to a List of lists. I can see I would be able to achieve this using one of the methods recommended in answer referenced above, namely:

str = "[[0,0,0],[0,0,1],[1,1,0]]"
strs = str.replace('[','').split('],')
lists = [map(int, s.replace(']','').split(',')) for s in strs]

But wondering if there is a better method in Dart but struggling to fnd any online?

like image 328
SSS Avatar asked May 05 '17 17:05

SSS


1 Answers

You can use the JSON decoder

import 'dart:convert';

...

var lists = json.decode('[[123],[122],[411]]');

DartPad example

update

final regExp = new RegExp(r'(?:\[)?(\[[^\]]*?\](?:,?))(?:\])?');
final input = '[[sometext],[122],[411]]';
final result = regExp.allMatches(input).map((m) => m.group(1))
  .map((String item) => item.replaceAll(new RegExp(r'[\[\],]'), ''))
  .map((m) => [m])
  .toList();
print(result);

DartPad example

like image 90
Günter Zöchbauer Avatar answered Oct 06 '22 23:10

Günter Zöchbauer