writeJson method

Map<String, dynamic> writeJson (
  1. Map<String, dynamic> json,
  2. String path,
  3. dynamic value
)

Writes the given 'value' at 'path' into the given 'json' map. If 'path' does not yet exist in the map, it will be created.

Implementation

static Map<String, dynamic> writeJson(
    Map<String, dynamic> json, String path, dynamic value) {
  if (path == null) {
    return json;
  }
  List<String> keys = path.split('\.');
  // --- new map with last key : value
  Map<String, dynamic> map = {keys[keys.length - 1]: value};
  for (int i = keys.length - 2; i >= 0; i--) {
    map = {keys[i]: map};
  }
  if (json == null) {
    return map;
  }
  Map<String, dynamic> innerJson = json;
  for (int i = 0; i < keys.length; i++) {
    if (innerJson.containsKey(keys[i]) && innerJson[keys[i]] is Map) {
      innerJson = innerJson[keys[i]];
      map = map[keys[i]];
    } else {
      innerJson.addAll(map);
      break;
    }
  }
  return json;
}