Skip to content

unwrap()

Peel nested JSON-as-string encoding in one call.

Signature

php
JsonFast::unwrap(
    string $json,
    ?int $maxDepth = 3,
    ?int $output = OUTPUT_ARRAY
): mixed

Parameters

NameTypeDefaultDescription
$jsonstringJSON text (often a quoted string containing JSON)
$maxDepth?int3Maximum decode layers
$output?intOUTPUT_ARRAYOutput mode

Returns

The innermost decoded value after up to $maxDepth unwrap passes. Type depends on content and $output (array, string, or stdClass).

The problem it solves

json_decode() succeeds but you still get a string:

php
$raw = '"{\"user\":{\"id\":42}}"';
$data = json_decode($raw, true);
// string, not array — need another decode

Common causes:

  • APIs that JSON-encode an already-stringified payload
  • Database columns with json_encode(json_encode($data))
  • Webhooks that wrap the body again for transport

Examples

Single layer:

php
$payload = '"{\"status\":\"ok\",\"count\":3}"';
$data = JsonFast::unwrap($payload);
// ['status' => 'ok', 'count' => 3]

Nested field from an API:

php
$outer = json_decode($httpResponse, true);
$config = JsonFast::unwrap($outer['data'], maxDepth: 5);

Object output:

php
$event = JsonFast::unwrap($webhookBody, maxDepth: 5, output: JsonFast::OUTPUT_OBJECT);
echo $event->type;

unwrap() vs repair()

SituationUse
Clean double-encoded string, valid outer syntaxunwrap()
Double-encoding mixed with comments, trailing commas, etc.repair() with REPAIR_DOUBLE_ENCODED

Native tools, weird experiments, and practical performance work.