Skip to contents

Creates an intermediate definition indicating that a JSON value can either conform to the specified structure_definition or be JSON null. This is typically used within s_map() to define fields that are not required to have a non-null value.

Usage

s_optional(structure_definition)

Arguments

structure_definition

The structure definition that the JSON value should conform to if it is not null. This should be the result of another s_* function call (e.g., s_integer(), s_string(), s_map(...)).

Value

An intermediate list representing the optional structure definition.

Examples

# Define a map where 'description' is optional (can be string or null)
map_with_optional <- s_map(
  id = s_integer(),
  description = s_optional(s_string())
)
built_optional <- build_structure(map_with_optional)
str(built_optional)
#> Class 'Structure' <externalptr> 
# Expected (simplified):
# list(type = "map",
#      value = list(id = list(type = "integer"),
#                   description = list(type = "optional",
#                                      value = list(type = "string"))),
#      ...)

# Define a vector where elements can be integers or null
vec_optional_elements <- s_vector(s_optional(s_integer()))
build_structure(vec_optional_elements)
#> Vector(
#>     Optional(
#>         Integer,
#>     ),
#> )
# Expected (simplified):
# list(type = "vector",
#      value = list(type = "optional", value = list(type = "integer")))

# --- Parsing Examples (see ?parse_json) ---

# Field present and valid
json_present <- '{"id": 1, "description": "A product"}'
parse_json(json_present, built_optional)
#> $id
#> [1] 1
#> 
#> $description
#> [1] "A product"
#> 
# Output: list(id = 1L, description = "A product")

# Optional field is null
json_null <- '{"id": 2, "description": null}'
parse_json(json_null, built_optional)
#> $id
#> [1] 2
#> 
#> $description
#> NULL
#> 
# Output: list(id = 2L, description = NULL)

# Optional field is missing (this causes an error by default with maps)
# Note: Optionality here means "can be null", not "can be absent".
# The 'missing field' error takes precedence unless the field is truly absent
# from the structure definition itself (which isn't the case here).
json_missing <- '{"id": 3}'
try(parse_json(json_missing, built_optional))
#> $id
#> [1] 3
#> 
# Expected: Error about missing field "description"

# Parsing a vector with optional elements
json_vec_opt <- '[10, null, 30, null]'
parse_json(json_vec_opt, build_structure(vec_optional_elements))
#> [1] 10 NA 30 NA
# Output: list(10L, NULL, 30L, NULL)