Skip to content
← Back to Snippets
Code

Handle JSON Encode and Decode Errors

Encodes and decodes JSON while checking json_last_error() and returning readable error messages.

Purpose

Encodes and decodes JSON while checking json_last_error() and returning readable error messages.

Snippet details

ContextJsonLevelProductionCopy-and-paste statusMarked safe after review.

Categories

  • Forms and Validation

Code

<?php

/*
 * Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
 * Free for personal and internal use. Paid project use requires visible credit
 * to Jeffery L. Paris. Corporate use requires a paid license fee unless a
 * separate written license states otherwise.
 */

/**
 * Handle JSON Encode and Decode Errors.
 *
 * Purpose:
 * Encodes an array to JSON, decodes JSON back to an array, and reports errors.
 *
 * @param array $payload Payload to encode.
 * @param string $json_text JSON text to decode.
 * @return array JSON operation report.
 */
function ogSnippetHandleJsonErrors(array $payload, string $json_text): array {
	$report = array(
		'encoded' => '',
		'encode_ok' => false,
		'encode_error' => '',
		'decoded' => array(),
		'decode_ok' => false,
		'decode_error' => ''
	);

	$encoded = json_encode($payload);

	if (json_last_error() === JSON_ERROR_NONE && is_string($encoded) === true) {
		$report['encoded'] = $encoded;
		$report['encode_ok'] = true;
	} else {
		$report['encode_error'] = json_last_error_msg();
	}

	$decoded = json_decode($json_text, true);

	if (json_last_error() === JSON_ERROR_NONE && is_array($decoded) === true) {
		$report['decoded'] = $decoded;
		$report['decode_ok'] = true;
	} else {
		$report['decode_error'] = json_last_error_msg();
	}

	return $report;
}

$json_report = ogSnippetHandleJsonErrors(
	array('ship' => 'Serenity', 'status' => 'flying'),
	'{"gate":"open","chevron":7}'
);

if ($json_report['encode_ok'] === true && $json_report['decode_ok'] === true) {
	echo 'JSON encode and decode succeeded.';
} else {
	echo 'JSON operation failed.';
}