{"record":{"id":"3daff860dcab51db","repo":"phalcon/cphalcon","slug":"json-encode-error-message","errorCode":null,"errorMessage":"json_encode error: {message}","messagePattern":"json_encode error: (.+?)","errorType":"exception","errorClass":"Phalcon\\Support\\Helper\\Json\\Exceptions\\JsonEncodeError","httpStatus":null,"severity":"error","filePath":"phalcon/Support/Helper/Json/Encode.zep","lineNumber":52,"sourceCode":"    use EncodeTrait;\n\n    /**\n     * @param int<1, max> $depth   Recursion depth.\n     *\n     * @throws JsonEncodeError if the JSON cannot be encoded.\n     * @link https://www.php.net/manual/en/function.json-encode.php\n     */\n    public function __invoke(\n        var data,\n        int options = 79,\n        int depth = 512\n    ) -> string {\n        var ex;\n\n        try {\n            return this->toEncode(data, options, depth);\n        } catch JsonException, ex {\n            throw new JsonEncodeError(ex->getMessage(), ex->getCode(), ex);\n        }\n    }\n}\n","sourceCodeStart":34,"sourceCodeEnd":56,"githubUrl":"https://github.com/phalcon/cphalcon/blob/b7419de9cd0a8a3f48441ead84c9f8415d463e25/phalcon/Support/Helper/Json/Encode.zep#L34-L56","documentation":"Phalcon\\Support\\Helper\\Json\\Encode wraps json_encode with throw-on-error semantics and rethrows any JsonException as Phalcon\\Support\\Helper\\Json\\Exceptions\\JsonEncodeError (\"json_encode error: {message}\"). It fires when json_encode fails: malformed UTF-8 in strings ('Malformed UTF-8 characters, possibly incorrectly encoded'), NAN/INF floats, resources, arrays with mixed keys? no — primarily recursion ('Recursion detected') and depth over 512.","triggerScenarios":"(new Encode())($row) where $row contains a latin1-bytes string from a misconfigured DB column; encoding a graph with circular references (parent/child objects cast to arrays); NAN/INF leaking from calculations; depth > 512.","commonSituations":"DB connections not set to UTF-8 producing invalid byte sequences; scientific/financial feeds delivering INF/NAN; entity graphs with back-references being serialized for caches or APIs.","solutions":["Fix data encoding at the source: set UTF-8 on DB connections/files, or repair strings with mb_convert_encoding($v, 'UTF-8', 'UTF-8')","Replace non-finite floats: is_finite($v) ? $v : null","For circular graphs, implement JsonSerializable or unset back-references; raise $depth for legitimately deep structures","As a last resort pass JSON_PARTIAL_OUTPUT_ON_ERROR via $options and accept placeholder output"],"exampleFix":"// before\n$json = (new Encode())($row); // 'json_encode error: Malformed UTF-8 characters'\n\n// after\narray_walk_recursive($row, function (&$v) {\n    if (is_string($v) && !mb_check_encoding($v, 'UTF-8')) {\n        $v = mb_convert_encoding($v, 'UTF-8', 'UTF-8');\n    } elseif (is_float($v) && !is_finite($v)) {\n        $v = null;\n    }\n});\n$json = (new Encode())($row);","handlingStrategy":"validation","validationCode":"array_walk_recursive($data, function (&$value) {\n    if (is_float($value) && !is_finite($value)) {\n        $value = null; // NAN/INF are not JSON-encodable\n    } elseif (is_string($value) && !mb_check_encoding($value, 'UTF-8')) {\n        $value = mb_convert_encoding($value, 'UTF-8', 'UTF-8');\n    } elseif (is_resource($value)) {\n        $value = null;\n    }\n});\n\n$json = (new Encode())($data);","typeGuard":"function isJsonEncodableValue($value): bool\n{\n    if (is_float($value)) {\n        return is_finite($value);\n    }\n\n    return !is_resource($value)\n        && (!is_string($value) || mb_check_encoding($value, 'UTF-8'));\n}","tryCatchPattern":"use Phalcon\\Support\\Helper\\Json\\Exceptions\\JsonEncodeError;\n\ntry {\n    $json = $encode($data);\n} catch (JsonEncodeError $e) {\n    // \"json_encode error: Malformed UTF-8 characters...\" / \"Recursion detected\"\n    $logger->error($e->getMessage());\n    $json = null;\n}","preventionTips":["Set UTF-8 end to end: DB connection charset, file reads, HTTP output","Reject or substitute non-finite floats before data reaches encoders","Implement JsonSerializable on entities with back-references instead of relying on deep casting","Raise $depth deliberately for known-deep structures rather than hoping 512 suffices"],"tags":["phalcon","json","encode","utf-8","php"],"backgroundTag":"json-encode-failed","analyzedSha":"b7419de9cd0a8a3f48441ead84c9f8415d463e25","analyzedAt":"2026-08-21T06:21:18.811Z","schemaVersion":2},"datasetVersion":"2026-08-21T11:28:35.574Z"}