PHP's json_last_error in TypeScript

✓ Verified: PHP 8.3
Examples tested against actual runtime. CI re-verifies continuously. Only documented examples are tested.

How to use

Install via yarn add locutus and import: import { json_last_error } from 'locutus/php/json/json_last_error'.

Or with CommonJS: const { json_last_error } = require('locutus/php/json/json_last_error')

Use a bundler that supports tree-shaking so you only ship the functions you actually use. Vite, webpack, Rollup, and Parcel all handle this. For server-side use this is less of a concern.

Examples

These examples are extracted from test cases that automatically verify our functions against their native counterparts.

#codeexpected result
1json_last_error()0

Dependencies

This function uses the following Locutus functions:

Here's what our current TypeScript equivalent to PHP's json_last_error looks like.

import { getPhpRuntimeNumber } from '../_helpers/_phpRuntimeState.ts'

export function json_last_error(): number {
// discuss at: https://phpjs.org/functions/json_last_error/
// parity verified: PHP 8.3
// original by: Brett Zamir (https://brett-zamir.me)
// example 1: json_last_error()
// returns 1: 0

// JSON_ERROR_NONE = 0
// max depth limit to be removed per PHP comments in json.c (not possible in JS?):
// JSON_ERROR_DEPTH = 1
// internal use? also not documented:
// JSON_ERROR_STATE_MISMATCH = 2
// [\u0000-\u0008\u000B-\u000C\u000E-\u001F] if used directly within json_decode():
// JSON_ERROR_CTRL_CHAR = 3
// but JSON functions auto-escape these, so error not possible in JavaScript
// JSON_ERROR_SYNTAX = 4

return getPhpRuntimeNumber('last_error_json', 0)
}

Improve this function

Locutus is a community effort following The McDonald's Theory: we ship first iterations, hoping others will improve them. If you see something that could be better, we'd love your contribution.

View on GitHub · Edit on GitHub · View Raw


« More PHP json functions


Star