How to Read JSON file in Dart console app?

Viewed 1362

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.

3 Answers

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'];
}

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);
    final users = data['users'];
    // ... 
}

Below is the sample code which you can use to synchronously read a text/json file as a string, displays its content and creates corresponding objects. This will work without using any flutter classes.
For reading JSON/txt file,user 'dart:io' package. Once the file has been read as a string, use JsonDecoder class to convert the json into corresponding data model objects

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

const String FILEPATH = "C:\\test\\dartlang\\users.json";
const JsonDecoder decoder = JsonDecoder();

class USER {
  int? id;
  String? user;
  String? password;

  //{ } - implies named arguments
  USER({this.id, this.user, this.password});

  @override
  String toString() {
    return "{id:$id,user:$user,password:$password}";
  }
}


void main() {
     List<USER>? eMP; 
    //synchronously read file contents
    var jsonString = File(FILEPATH).readAsStringSync();
    //print(jsonString);
    //pass the read string to JsonDecoder class to convert into corresponding Objects 
    final Map<String, dynamic> jsonmap = decoder.convert(jsonString);
    
    //DataModel - key = "users", value = "ARRAY of Objects"
    var value = jsonmap["users"];
    if (value != null) {
      eMP = <USER>[];
      //Each item in value is of type::: _InternalLinkedHashMap<String, dynamic>
      value.forEach((item) => eMP?.add(new USER(id:item["id"],user:item["user"],password:item["password"] )));
    }
    eMP?.forEach((element) => print(element));
}

Save the following json file in your filepath.

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