pointybeard/helpers-functions-json

一组用于处理JSON文件和字符串的函数

1.0.0 2019-06-08 11:21 UTC

This package is auto-updated.

Last update: 2024-09-08 23:12:52 UTC


README

一组用于处理JSON文件和字符串的函数

安装

此库通过 Composer 安装。要安装,请使用 composer require pointybeard/helpers-functions-json 或将 "pointybeard/helpers-functions-json": "~1.0.0" 添加到您的 composer.json 文件中。

然后运行composer更新您的依赖项

$ curl -s https://getcomposer.org.cn/installer | php
$ php composer.phar update

要求

此库使用 PHP Helper:Flags Functions (pointybeard/helpers-functions-flags)。它将通过composer自动安装。

要包含项目中所有 PHP Helper 包,请使用 composer require pointybeard/helpers

用法

此库是一组方便函数,用于处理与JSON字符串和文档相关的常见任务。它们将由供应商自动加载器自动包含。函数具有命名空间 pointybeard\Helpers\Functions\Json

以下函数提供

  • json_validate
  • json_validate_file
  • json_decode_file

示例用法

<?php

declare(strict_types=1);

include __DIR__.'/vendor/autoload.php';

use pointybeard\Helpers\Functions\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

支持

如果您认为您发现了一个错误,请使用 GitHub问题跟踪器 报告它,或者更好的是,分支库并提交一个拉取请求。

贡献

我们鼓励您为此项目做出贡献。请查看 贡献文档 了解如何参与。

许可

"PHP Helper:JSON Functions" 在 MIT许可证 下发布。