setJsonPathValue function

Object? setJsonPathValue(
  1. Object? root,
  2. List<PathKey> keys,
  3. Object? value
)

Sets keys in JSON root (copied along the way) to value. Maps are created for missing keys; an index past a list's end (or a list missing) fails. Null when it can't be set.

Implementation

Object? setJsonPathValue(Object? root, List<PathKey> keys, Object? value) {
  if (keys.isEmpty) return value;
  final k = keys.first;
  final rest = keys.sublist(1);
  if (k is int) {
    final l = readList(root);
    if (l == null || k >= l.length) return null;
    final v = setJsonPathValue(l[k], rest, value);
    if (v == null && value != null) return null;
    return [...l]..[k] = v;
  }
  if (k == everyItem) {
    final l = readList(root);
    if (l == null) return null;
    return [for (final item in l) setJsonPathValue(item, rest, value) ?? item];
  }
  // A key into a list selects the item with that id.
  if (readList(root) case final List<Object?> l) {
    final i = l.indexWhere((item) => readMap(item)?['id'] == k);
    if (i < 0) return null;
    return setJsonPathValue(l, [i, ...rest], value);
  }
  final m = readMap(root) ?? const <String, Object?>{};
  final v = setJsonPathValue(m[k], rest, value);
  if (v == null && rest.isNotEmpty) return null;
  return {...m, k as String: v};
}