PHP code example of pointybeard / helpers-functions-json

1. Go to this page and download the library: Download pointybeard/helpers-functions-json library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

pointybeard / helpers-functions-json example snippets




declare(strict_types=1);

ns\Json;

/* Example 1: Check if valid string is valid JSON **/
var_dump(Json\json_validate('{"person": {"name": "Sarah Smith"}}'));
// bool(true)

/** Example 2: Check if invalid string is valid JSON **/
$isValid = Json\json_validate('{"person": {"name":}', $code, $message);
var_dump($isValid, $code, $message);
// bool(false)
// int(4)
// string(12) "Syntax error"

/** Example 3: Check if file contains valid JSON **/
$tmp = tempnam(sys_get_temp_dir(), 'JsonFunctionTest');
file_put_contents($tmp, '{"person": {"name": "Sarah Smith"}}');
var_dump(Json\json_validate_file($tmp));
// bool(true)

/* Example 4: Decode contents of valid JSON file **/
var_dump(Json\json_decode_file($tmp));
// class stdClass#2 (1) {
//   public $person =>
//   class stdClass#3 (1) {
//     public $name =>
//     string(11) "Sarah Smith"
//   }
// }

/* Example 5: Validate file containing invalid JSON **/
file_put_contents($tmp, '{"person": {"name": {"name": "Broken JSON}');
$isValid = Json\json_validate_file($tmp, $code, $message);
var_dump($isValid, $code, $message);
// bool(false)
// int(3)
// string(53) "Control character error, possibly incorrectly encoded"

/* Example 6: Attempt to decode file containing invalid JSON **/
try {
    var_dump(Json\json_decode_file($tmp));
} catch (JsonException $ex) {
    echo $ex->getMessage().PHP_EOL;
}
// Control character error, possibly incorrectly encoded

/** Example 7: Attempt to validate non-existent JSON file **/
$isValid = Json\json_validate_file('nonexistent/file.json', $code, $message);
var_dump($isValid, $code, $message);
// bool(false)
// NULL
// string(42) "File nonexistent/file.json is not readable"

/* Example 8: Attempt to decode non-existent JSON file **/
Json\json_decode_file('nonexistent/file.json');
// Fatal error: Uncaught JsonException: The file nonexistent/file.json is not readable in /path/to/helpers-functions-json/src/Json/Json.php on line 82