PHP's json_decode 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_decode } from 'locutus/php/json/json_decode'.

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

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_decode('[ 1 ]')[1]

Notes

  • Uses the host JSON.parse implementation required by Locutus’ runtime target.

Dependencies

This function uses the following Locutus functions:

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

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

type JsonPrimitive = string | number | boolean | null
type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue }

export function json_decode<T = JsonValue>(strJson: string): T | null {
// discuss at: https://phpjs.org/functions/json_decode/
// parity verified: PHP 8.3
// original by: Public Domain (https://www.json.org/json2.js)
// reimplemented by: Kevin van Zonneveld (https://kevin.vanzonneveld.net)
// improved by: T.J. Leahy
// improved by: Michael White
// note 1: Uses the host JSON.parse implementation required by Locutus' runtime target.
// example 1: json_decode('[ 1 ]')
// returns 1: [1]

const json = typeof JSON === 'object' && JSON !== null ? JSON : null
const parse = json?.parse
if (typeof parse !== 'function') {
setPhpRuntimeEntry('last_error_json', 4)
return null
}

try {
const parsed = parse.call(json, strJson)
setPhpRuntimeEntry('last_error_json', 0)
return parsed
} catch (err) {
if (!(err instanceof SyntaxError)) {
throw new Error('Unexpected error type in json_decode()')
}

// usable by json_last_error()
setPhpRuntimeEntry('last_error_json', 4)
return null
}
}

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