operator [] method

Json operator [](
  1. dynamic key
)

Returns a Json wrapping the data under key. If key does not exist, returns a empty Json instance with an exception

Implementation

Json operator [](dynamic key) {
  if ((key is! String && key is! int) || (_rawValue is! List && _rawValue is! Map)) {
    var result = jsonNull;
    result.exception = exception ?? JsonException(JsonError.wrongType);
    return result;
  }

  if (_rawValue is List) {
    List rawList = _rawValue as List;
    late int index;

    if (key is String) {
      try {
        index = int.parse(key);
      } catch (_) {
        var result = jsonNull;
        result.exception = exception ??
            JsonException(JsonError.wrongType, userReason: 'JSON Error: index must be int, ${key.runtimeType} given');
        return result;
      }
    } else {
      index = key as int;
    }

    if (index < 0 || index >= rawList.length) {
      var result = jsonNull;
      result.exception = exception ??
          JsonException(JsonError.indexOutOfBounds, userReason: 'JSON Error: index `$index` is out of bounds');
      return result;
    }

    return Json.fromDynamic(rawList[index], initial: false);
  } else if (_rawValue is Map) {
    Map rawMap = _rawValue as Map;
    late String index;

    if (key is String) {
      index = key;
    } else {
      index = '$key';
    }

    var result = Json.fromDynamic(rawMap[index], initial: false);

    if (!rawMap.containsKey(index)) {
      result.exception =
          exception ?? JsonException(JsonError.notExist, userReason: 'JSON Error: key `$index` does not exists');
    }

    return result;
  }

  // Unreachable
  assert(false, 'Should be unreachable');

  return jsonNull;
}