Ad

How To Access Last Index Of Nested Array

I'm trying to figure out how to access the last index of a nested array. The array I am working with is provided by an API call and is VERY LARGE so I'll shorten it below for convenience.

The array:

{

"result": {
    "86400": [
      [
        1381190400,
        123.610000,
        123.610000,
        123.610000,
        123.610000,
        0.100000,
        0.0
      ],
      [
        1381276800,
        123.610000,
        124.190000,
        123.900000,
        124.180000,
        3.991600,
        0.0
      ],
     ...

      [
        1600646400,
        11078,
        11078,
        10906.9,
        10950.4,
        623.00835437,
        6841501.73480653
      ]
    ]
  },

"allowance": {
    "cost": 0.015,
    "remaining": 9.985,
    "upgrade": "For unlimited API access, create an account at ________"
  }
}

I would like to access the last index of ['result']['86400'] , which contains:

 [
        1600646400,
        11078,
        11078,
        10906.9,
        10950.4,
        623.00835437,
        6841501.73480653
      ]

I am using Flutter in my code, so here is what I have tried:

http.Response historicalResponse = await http.get(historicalRequestURL);

var decodedHistorical = jsonDecode(historicalResponse.body);

var historicalPrice = decodedHistorical['result']['86400'.length - 1][0];

print(historicalPrice);

This causes a few errors stating:

"NoSuchMethodError: The method '[]' was called on null."
"Receiver: null"
"Tried calling: [](0)"

I believe ['86400'.length - 1] is causing the error.

I have also tried using

var historicalPrice = decodedHistorical['result']['86400'][decodedHistorical.length - 1][0];

instead. This doesn't cause an error but it gives me the length of the outer array, which is 2 but I need the length of the inner array named '86400'.

Ad

Answer

You should implement below way

 void parseJson() async {
    http.Response historicalResponse = await http.get(historicalRequestURL);
    Map decodedHistorical = jsonDecode(historicalResponse.body);
    List selectedMap = decodedHistorical['result']['86400'];
    var finalValue = selectedMap.last;
    print(finalValue);
  }
Ad
source: stackoverflow.com
Ad