jsonflutterlistdartjsonparser

Read json file and parse the data key and value using flutter


I'm currently trying to read json from azure blob storage which I'm able to do.

Now I want to parse the data and display or print the data in Flutter (dart language). Below is the code.

    Future<void> main() async {
     String sasUrl = 'blob file url sas token';
    try {
      // Send HTTP GET request to the SAS URL
      final response = await http.get(Uri.parse(sasUrl));
    

      if (response.statusCode == 200) {
      // Parse response body as bytes
      String responsebody  = response.body;

      List<String> lines = LineSplitter().convert(responsebody) ;
      
      lines.forEach((line) {
        Map<String, dynamic> jsonData = json.decode(line);
        print(jsonData);
        jsonData.forEach((key, value) {
          print('$key: $value');
        });
      });

      // Handle the data as needed
    } else {
      print('Failed to fetch data: ${response.statusCode}');
    }
  } catch (e) {
    print('Error fetching data: $e');
  }
}

The error I'm getting is the following

Error fetching data: Expected a value of type 'Map<String, dynamic>', but got one of type 'List'

Is there any way to solve this I have tried using casting but didn't work.


Solution

  • The first thing is you need not to use line splitter in order to parse json. Just pass response.body to jsonDecode

    And the other thing is you are getting a list after parsing the json. So you must change this line

    Map<String, dynamic> jsonData = json.decode(line);

    to

    Map<String, dynamic> jsonData = json.decode(response.body)[0];
    

    then you will get the desired result I suppose. So the final code will be like:

     Future<void> main() async {
     String sasUrl = 'blob file url sas token;
    try {
      // Send HTTP GET request to the SAS URL
      final response = await http.get(Uri.parse(sasUrl));
    
    
      if (response.statusCode == 200) {
      // Parse response body as bytes
      String responsebody  = response.body;
    
      
        Map<String, dynamic> jsonData = json.decode(responsebody)[0];
        print(jsonData);
        jsonData.forEach((key, value) {
          print('$key: $value');
        });
      
    
      // Handle the data as needed
    } else {
      print('Failed to fetch data: ${response.statusCode}');
    }
    
    
     } catch (e) {
        print('Error fetching data: $e');
      }
    }