JSON

json.clone

Clones a value by encoding it with json.encode semantics and decoding the generated JSON back into Lua values.

Syntax

json.clone(value: any, options?: EncodeOptions): any

Arguments

NameTypeDescription
valueanyValue to encode and decode. Supported JSON values round-trip with JSON; unsupported types encode as null unless encode options request an error.
options?EncodeOptionsOptional encode options passed to the encode step, such as sortKeys, emptyTableAsArray, errorOnUnsupported, encodeInvalidNumbersAsNull, maxDepth, pretty, and indent.

Returns

NameTypeDescription
cloneanyDecoded value produced from the encoded JSON. Objects and arrays are new tables with JSON kind markers from the decoder; JSON null values decode to json.null.

Description

Clones a value by encoding it with json.encode semantics and decoding the generated JSON back into Lua values.

Call it with 2 parameter(s): value, options. The argument table explains which values are required and which ones only refine the behavior.

It returns clone (any). Use the returns table to separate successful values from nil results and recoverable errors.

Example

Round-trip a JSON-compatible value through json.encode and json.decode before changing nested values.

local original = {
    profile = { name = "Guest" },
}

local copy = json.clone(original)
copy.profile.name = "Developer"

print(original.profile.name)
print(copy.profile.name)
print(json.type(copy))

Types

EncodeOptions

Controls JSON serialization and formatting.

pretty? boolean Enables formatted, multi-line JSON output.sortKeys? boolean Sorts object keys before encoding.emptyTableAsArray? boolean Encodes an empty table as an array instead of an object.errorOnUnsupported? boolean Raises an error instead of substituting unsupported values.encodeInvalidNumbersAsNull? boolean Encodes NaN and infinite numbers as JSON null.maxDepth? integer Sets the maximum nesting depth, clamped from 1 to 4096.indent? string Sets the indentation string, limited to 32 characters.