fromJsonChecked static method

Result<Json, String> fromJsonChecked(
  1. Object? value, {
  2. String? getter,
  3. bool isRoot = true,
})

Creates a Json from a valid Json value. Similar to fromJson but does not throw when value could not be coerced into a Json, it returns an error message instead

Implementation

static Result<Json, String> fromJsonChecked(
  Object? value, {
  String? getter,
  bool isRoot = true,
}) {
  final _errPrefix = getter == null
      ? 'value'
      : isRoot
          ? getter
          : '[$getter]';
  return resultCtx(
    (rctx) {
      if (value == null) {
        return const JsonNone();
      } else if (value is Map<String, Object?>) {
        return Json.map(value.map(
          (key, value) => MapEntry(
            key,
            rctx.unwrap(fromJsonChecked(
              value,
              getter: key,
              isRoot: false,
            )),
          ),
        ));
      } else if (value is List<Object?>) {
        return Json.list(
          value
              .mapIndexed((index, value) => rctx.unwrap(
                    fromJsonChecked(
                      value,
                      getter: index.toString(),
                      isRoot: false,
                    ),
                  ))
              .toList(),
        );
      } else if (value is Json) {
        return value;
      } else if (value is num) {
        return Json.number(value);
      } else if (value is bool) {
        return Json.boolean(value);
      } else if (value is String) {
        if (isRoot) {
          try {
            final Object? decoded = jsonDecode(value);
            return rctx.unwrap(fromJsonChecked(
              decoded,
              getter: getter,
              isRoot: false,
            ));
          } catch (_) {}
        }
        return Json.str(value);
      } else {
        rctx.throwErr(' = $value is not a valid JSON');
      }
    },
    mapErr: (err) => '$_errPrefix$err',
  );
}