0

I want to convert a string to multi-level list, but I cannot find a efficient way to do.

From String: [[1,2,3],[1,2]]

To List: List< List < int>>

1
  • You can checkout QuickType to parse your JSON string. It will generate the model for the required language. Commented May 29, 2020 at 6:49

3 Answers 3

1

Try this as a funtion

List<List<int>> convert(String val){
    List<List<int>> list = [];
  jsonDecode(val).forEach((mainList) {
    List<int> subList = [];
    mainList.forEach((sList) {
      subList.add(sList);
    });
    list.add(subList);
  });
  return list;
}

Also import dart:convert;

Sign up to request clarification or add additional context in comments.

Comments

0
String str = '[[1,2,3],[1,2]]';
  List<List<int>> list=[];
  for(String s in str.split('],[')){
    List<int> l = [];
    String formattedString = s.replaceAll('[','').replaceAll(']','');
    for(String innerS in formattedString.split(',')){
        l.add(int.parse(innerS));
      print(l);
    }
    list.add(l);
  }

Output: [[1, 2, 3], [1, 2]]

Comments

0

Shorter version:

import 'dart:convert';

void main() {
  var jsonMap = "[[1,2,3],[1,2]]";
  List<List<int>> items = (jsonDecode(jsonMap) as List).map((lst) => 
      (lst as List).map((i) => (i as int)).toList()).toList();
  print(items);
}

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.