Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to Read JSON file in Dart console app?

This is a full-console app in dart. Its not flutter.
I need to import data from a local json file and send it as response. I need to read the data as array of Map in dart. The data is in following format.

{    
"users":[
       {
          "id":1,
          "user":"user1",
          "password":"p455w0rd"
       },
       {
          "id":2,
          "user":"user2",
          "pass":"p455w0rd"
       }
  ] 
}

Every where I see the Flutter example which imports flutter/services as rootBundle to read into the JSON file. I do not find a way to implement this in pure dart.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use dart:io and dart:convert.

Simple example below. Remember to add exception handling if the file does not exist or has wrong format.

import 'dart:convert';
import 'dart:io';

Future<List<Map>> readJsonFile(string filePath) async {
  var input = await File('file.txt').readAsString();
  var map = jsonDecode(input);
  return map['users'];
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading