Skip to contents

Processes a structure definition created using the s_* helper functions (like s_integer(), s_map(), s_vector()) into a final, validated representation required by the parse_json() function.

Usage

build_structure(x)

Arguments

x

The structure definition created using s_* functions. This defines the expected schema of the JSON data (e.g., s_map(id = s_integer())).

Value

An object representing the finalized structure definition. This object is specifically formatted for use as the structure argument in the parse_json() function. The internal details of this object are not typically needed by the user.

Details

This function serves two main purposes:

  1. Validation: It checks the user-provided structure definition for correctness before attempting to parse any JSON. This includes verifying that s_map() arguments are correctly named and use valid s_* definitions, that s_vector() has a valid element_structure, and that nesting is consistent. Errors in the definition (like duplicate field names in s_map) will be caught at this stage.

  2. Preparation: It converts the user-friendly definition created with s_* functions into the specific internal format required by the efficient JSON parsing engine used in parse_json().

You must call build_structure() on your schema definition before passing it to parse_json().

Examples

# 1. Define the desired JSON structure using s_* functions
my_schema_definition <- s_map(
  product_id = s_string(),
  quantity = s_integer(),
  in_stock = s_logical(),
  attributes = s_vector(s_string())
)

# 2. Finalize and validate the definition
finalized_structure <- build_structure(my_schema_definition)
# finalized_structure is now ready to be used with parse_json()

# Example with nested structures
complex_definition <- s_map(
  order_id = s_integer(),
  customer = s_map(
    name = s_string(),
    email = s_string()
  ),
  items = s_vector(
    s_map(
      sku = s_string(),
      price = s_double()
    )
  )
)

validated_complex_structure <- build_structure(complex_definition)

# Use the built structure with parse_json (see ?parse_json examples)
json_data <- '{
  "product_id": "XYZ-123",
  "quantity": 5,
  "in_stock": true,
  "attributes": ["red", "large"]
}'
parsed_data <- parse_json(json_data, structure = finalized_structure)
print(parsed_data)
#> $product_id
#> [1] "XYZ-123"
#> 
#> $quantity
#> [1] 5
#> 
#> $in_stock
#> [1] TRUE
#> 
#> $attributes
#> [1] "red"   "large"
#>