2

I am facing a problem in flutter for converting JSON data as List<Map<String, dynamic>>.

rawJson =
        '[{"value":"1","label":"red"}, {"value":"2","label":"Green"}, {"value":"3","label":"Yellow"}]';

This data need to convert as List<Map<String, dynamic>>

The following code is working, but need help top things.

List<Map<String, dynamic>> _items = [
    {
      'value': '1',
      'label': 'Red',
    },
    {
      'value': '2',
      'label': 'Green',
    },
    {
      'value': '3',
      'label': 'Yellow',
    },
  ];
1
  • i don't understand about you't question, you'r code work fine. what do you want ? Commented Sep 3, 2021 at 16:41

2 Answers 2

4

You need to cast your json like this:

var rawJson = '[{"value":"1","label":"red"}, {"value":"2","label":"Green"}, {"value":"3","label":"Yellow"}]';

List<Map<String, dynamic>> output = (json.decode(rawJson) as List).cast();
// or
List<Map<String, dynamic>> output = List.from(json.decode(rawJson) as List);
Sign up to request clarification or add additional context in comments.

Comments

0

This is probably what your are looking for:

  var rawJson =
      '[{"value":"1","label":"red"}, {"value":"2","label":"Green"}, {"value":"3","label":"Yellow"}]';

  var iterableResult = (jsonDecode(rawJson) as List<dynamic>).map((element) =>
      {"value": int.parse(element['value']), "label": element['label']});
  var listResult = iterableResult.toList();
  print(listResult); // prints [{value: 1, label: red}, {value: 2, label: Green}, {value: 3, label: Yellow}]

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.