readJson method

dynamic readJson (
  1. Map<String, dynamic> json,
  2. String path
)

Reads a value from a nested map (json). The map is identified by a slash (/) separated path.

Map<String, dynamic> json = { 'user' : { 'name' : 'Hajo', 'bday' : '1964-09-21' },};
DateTime birthday = Datetime.parse( readJson( json, 'user/bday' ));

Implementation

static dynamic readJson(Map<String, dynamic> json, String path) {
  if (json == null || path == null) {
    return null;
  }
  List<String> keys = path.split('/');
  dynamic value = json;
  for (int i = 0; i < keys.length; i++) {
    if (value == null) return null;
    try {
      if (value is List) {
        // --- json element is a list [...]
        value = _readJsonFromList(value, keys[i]);
      } else {
        // --- json element is a value or an object {}
        value = value[keys[i]];
      }
    } catch (e) {
      print('path=$path i=$i value=$value -> ' + e.toString());
    }
  }
  return value;
}