Json.to_or
template<typename T, typename D = Nul>
requires convertible<Json, T> || convertible_map<Json, T, D> || convertible_array<Json, T, D>
T to_or( T default_result, D default_range_elem = D{} ) const noexcept;
Converts internal data to type T
(copy) and returns the provided default value on failure.
Extensive compile-time type checking ensures incompatible branches are eliminated during compilation.
Note: Runtime conversion may still fail due to JSON's dynamic typing, despite template instantiation being valid.
Important: This function doesn't handle allocation failures or constructor exceptions - these will propagate normally.
Conversion Rules
- Nul → Nul
- Obj → Obj
- Arr → Arr
- Str → Str
- Bol → Bol
- Num → Enum (rounded to nearest integer)
- Num → Integer types (rounded)
- Num → Floating-point types
- Any → Types with Json constructors
- Obj → Implicitly convertible types
- Arr → Implicitly convertible types
- Str → Implicitly convertible types
- Num → Implicitly convertible types
- Bol → Implicitly convertible types
- Nul → Implicitly convertible types (except bool)
- Obj → Convertible key-value types (element-wise)
- Arr → Convertible container types (element-wise)
- Returns provided default value
Parameters
T
: Target typedefault_result
: Fallback value returned on conversion failuredefault_range_elem
: Fallback value for failed element conversions (array/object only)
Exception Safety
No-throw guarantee.
Complexity
Linear time O(n) (full copy required)
Key characteristics: - Never throws for type mismatches (uses default value) - Still propagates memory/constructor exceptions - Same conversion rules as other variants but with default fallback -
Version
Since v3.0.0 .