unwrap()
Peel nested JSON-as-string encoding in one call.
Signature
php
JsonFast::unwrap(
string $json,
?int $maxDepth = 3,
?int $output = OUTPUT_ARRAY
): mixedParameters
| Name | Type | Default | Description |
|---|---|---|---|
$json | string | — | JSON text (often a quoted string containing JSON) |
$maxDepth | ?int | 3 | Maximum decode layers |
$output | ?int | OUTPUT_ARRAY | Output 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 decodeCommon 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()
| Situation | Use |
|---|---|
| Clean double-encoded string, valid outer syntax | unwrap() |
| Double-encoding mixed with comments, trailing commas, etc. | repair() with REPAIR_DOUBLE_ENCODED |
