jsonPathLookup function

Object? jsonPathLookup(
  1. Object? root,
  2. String path
)

Resolve a SQLite-style JSON path (e.g. $, $.a.b, $[0], $.a[1].b) against root. Returns null if any segment is missing.

Implementation

Object? jsonPathLookup(Object? root, String path) {
  if (!path.startsWith(r'$')) {
    throw FormatException('JSON path must start with \$: $path');
  }
  Object? cur = root;
  var i = 1;
  while (i < path.length) {
    final ch = path[i];
    if (ch == '.') {
      i++;
      final start = i;
      while (i < path.length && path[i] != '.' && path[i] != '[') {
        i++;
      }
      final key = path.substring(start, i);
      if (cur is Map) {
        cur = cur[key];
      } else {
        return null;
      }
    } else if (ch == '[') {
      final close = path.indexOf(']', i + 1);
      if (close < 0) {
        throw FormatException('Unterminated [ in JSON path: $path');
      }
      final idx = int.parse(path.substring(i + 1, close));
      if (cur is List) {
        if (idx < 0 || idx >= cur.length) return null;
        cur = cur[idx];
      } else {
        return null;
      }
      i = close + 1;
    } else {
      throw FormatException('Unexpected character in JSON path: $path');
    }
    if (cur == null) return null;
  }
  return cur;
}