Parses a JSON string and validates it against a schema created with build_structure()
.
Returns an R object reflecting the JSON content if valid, or throws a detailed error.
Arguments
- json_string
A character string containing the JSON input.
- structure
A structure definition created with
build_structure()
, based ons_*
functions.
Value
The parsed and validated data as an R object:
JSON objects → named
list
sJSON arrays → unnamed
list
sStrings, numbers, booleans → scalar R values (character, numeric, integer, logical)
Errors are raised for invalid syntax, type mismatches, missing or extra fields, duplicate keys, and integer overflows.
Details
Validation checks include:
Types: JSON values must match the declared structure (e.g., string vs integer).
Required fields: All fields in
s_map()
must be present.No extra fields: Additional fields not in the structure cause errors (unless
.ignore_extra_fields = TRUE
).Duplicate keys: Disallowed.
Integer range: Must fit within R's 32-bit integer limits for
s_integer()
.Homogeneous arrays: Elements in
s_vector()
must match the defined structure.
Parsing is powered by serde_json
in Rust for performance.
Examples
# Define and build a structure
schema <- build_structure(s_map(
id = s_integer(),
username = s_string(),
is_active = s_logical(),
scores = s_vector(s_double())
))
# Valid input
json <- '{"id":1,"username":"user","is_active":true,"scores":[9.5,8.0]}'
parse_json(json, schema)
#> $id
#> [1] 1
#>
#> $username
#> [1] "user"
#>
#> $is_active
#> [1] TRUE
#>
#> $scores
#> [1] 9.5 8.0
#>
# Common errors:
# - Invalid JSON
# - Wrong type (e.g., "id": "abc")
# - Missing fields
# - Unexpected extra fields
# - Integer overflow
# - Duplicate keys