Home > front end >  How can I parse this Json into a list in dart?
How can I parse this Json into a list in dart?

Time:06-23

this response is what I get from a get request.But I dont know how can I convert it and put it on a list.this is a response for ohlc request from coingecko api.I want to know how can I use it in dart.

[
  [
    1655830800000,
    21401.69,
    21401.69,
    21401.69,
    21401.69
  ],
  [
    1655832600000,
    21404.99,
    21404.99,
    21372.94,
    21394.43
  ],
]

CodePudding user response:

I must say I am not completely sure what kind of data structure you want this to parsed into. But the following solutions makes it a List<List<num>> which is the closest to the way we can represent the input:

import 'dart:convert';

void main() {
  List<dynamic> jsonObject = jsonDecode(jsonString) as List<dynamic>;

  List<List<num>> listOfListsOfDouble = [
    for (final jsonListOfDoubles in jsonObject)
      [
        for (final value in (jsonListOfDoubles as List<dynamic>))
          value as num
      ]
  ];

  listOfListsOfDouble.forEach(print);
  // [1655830800000, 21401.69, 21401.69, 21401.69, 21401.69]
  // [1655832600000, 21404.99, 21404.99, 21372.94, 21394.43]

  print(listOfListsOfDouble.runtimeType); // List<List<num>>
}

final jsonString = '''
[
  [
    1655830800000,
    21401.69,
    21401.69,
    21401.69,
    21401.69
  ],
  [
    1655832600000,
    21404.99,
    21404.99,
    21372.94,
    21394.43
  ]
]
'''

The reason I have used num is because your list contains a mix of values that can be represented as double or int. If we want to just convert any int to double and end up with List<List<double>> we can just change the code to:

  List<List<double>> listOfListsOfDouble = [
    for (final jsonListOfDoubles in jsonObject)
      [
        for (final value in (jsonListOfDoubles as List<dynamic>))
          (value as num).toDouble()
      ]
  ];

CodePudding user response:

What do you want to do with these values? From the request, you get a two-dimensional list with doubles. In the next step, you can parse it but this depends on what you want to get.

  • Related