PHP's json_last_error in JavaScript

How to use

You you can install via yarn add locutus and require this function via const json_last_error = require('locutus/php/json/json_last_error').

It is important to use a bundler that supports tree-shaking so that you only ship the functions that you actually use to your browser, instead of all of Locutus, which is massive. Examples are: Parcel, webpack, or rollup.js. For server-side use this is typically less of a concern.

Examples

Please note that these examples are distilled from test cases that automatically verify our functions still work correctly. This could explain some quirky ones.

#codeexpected result
1json_last_error()0

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

module.exports = function json_last_error() {
// discuss at: https://phpjs.org/functions/json_last_error/
// 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

const $global = typeof window !== 'undefined' ? window : global
$global.$locutus = $global.$locutus || {}
const $locutus = $global.$locutus
$locutus.php = $locutus.php || {}

return $locutus.php && $locutus.php.last_error_json ? $locutus.php.last_error_json : 0
}

A community effort

Not unlike Wikipedia, Locutus is an ongoing community effort. Our philosophy follows The McDonald’s Theory. This means that we assimilate first iterations with imperfections, hoping for others to take issue with-and improve them. This unorthodox approach has worked very well to foster fun and fruitful collaboration, but please be reminded to use our creations at your own risk. THE SOFTWARE IS PROVIDED "AS IS" has never been more true than for Locutus.

Now go and: [ View on GitHub | Edit on GitHub | View Raw ]


« More PHP json functions


Star