addElementToListOrInit function

dynamic addElementToListOrInit(
  1. Json json,
  2. SimpleJsonPath path,
  3. dynamic value
)

will create a list or add an element to an existing list

if path does exists but doesn't point to a list a JsonPathException will be thrown

Implementation

addElementToListOrInit(Json json, SimpleJsonPath path, dynamic value) {
  var parent = getByPath(json, path.sublist(0, path.length - 1));
  var key = path.last;

  if (parent[key] == null) {
    parent[key] = [value];
  } else {
    var listValue = parent[key];
    if (listValue.runtimeType != List) {
      throw JsonPathException('Expected element at ${path.prettyPrint()} to '
          'be a list, (or not being set at all) '
          'but a `${value.runtimeType}` was found,', code: 423423423);
    }
    listValue.add(value);
  }
}