flutterdart

Flutter get json data by index


I'm using Flutter and I have a JSON like below:

var json = {
  "key1": {"key": [1,2,3]},
  "key2": {"key": [4,5,7]},
  "key3": {"key": [8,9,10]},
}

I know that, for example, I can retrieve {"key": [4,5,7]} just by calling json["key2"].

But i'm asking, is it possible to retrieve it by using its index position, just like json[1]?


Solution

  • Yes, change your json to:

    {
      "values": [
        {
          "key": [1,2,3]
        },
        {
          "key": [4,5,7]
        },
        {
          "key": [8,9,10]
        }
      ]
    }
    

    And access it like: parsedJson["values"][0]

    In case you don't want to change your data structure, you can still do it like:

    import 'dart:core';
    
    void main() {
      var json = {
      "key1": {"key": [1,2,3]},
      "key2": {"key": [4,5,7]},
      "key3": {"key": [8,9,10]},
      };
      
      List<Map<String, List<int>>> jsonObjects = [];
      
      for (final name in json.keys) {
        final value = json[name];
        print('$value');
        jsonObjects.add(value);
      }
      
      print('$jsonObjects');
      
      print('Second object: ${jsonObjects[1]}');
    }
    

    You can try this at https://dartpad.dev