Home > Software design >  How to Read JSON file in Dart console app?
How to Read JSON file in Dart console app?

Time:03-27

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.

CodePudding user response:

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(filePath).readAsString();
  var map = jsonDecode(input);
  return map['users'];
}

CodePudding user response:

First import dart:convert.

You can parse data from a JSON file as follows:

Future<void> readJson() async {
        final String response = await rootBundle.loadString('assets/sample.json');
        final data = await json.decode(response);
        // ... 
    }
  • Related