9

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?

Community
  • 1
  • 1
SSS
  • 761
  • 2
  • 9
  • 19

1 Answers1

18

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

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Ah, this is exactly what I was trying. I see now though that the problem I had was I was converting text that was entered from a GUI. If you try: var lists = JSON.decode('[[sometext],[122],[411]]'); Then you get an error which must be the problem I was having. – SSS May 05 '17 at 17:36
  • That's because `sometext'` would require quotes to be valid JSON, but your question didn't contain text, only numbers ;-) – Günter Zöchbauer May 05 '17 at 17:39
  • Hey thanks so much! Sorry to ignore last answer - was busy failing to get to that same solution! – SSS May 05 '17 at 18:59
  • 1
    I believe it is now json.decode(), instead of JSON.decode(). – Tom O Nov 12 '20 at 10:14
  • Thanks. And what if it were `"['[123]','[122]','[411]']"` ? – sj_959 Dec 18 '21 at 15:13
  • Looks like you want to `json.decode()` every element of the array returned by the first `json.decode()` – Günter Zöchbauer Dec 20 '21 at 08:19