hgg/json
Composer 安装命令:
composer require hgg/json
包简介
Encode, decode, validate, handle errors (exceptions) and pretty print JSON
README 文档
README
Json is a collection of static methods to simplify working with JSON in PHP.
Features
- encode to JSON string with error handling
- decode from a string or file path containing valid JSON with error handling
- validate a JSON document against a JSON Schema
- pretty print a JSON string
Installation
NOTE:
The json-schema library version used here is currently a fork so you need to add the following to your composer.json file.
"repositories": [ { "type": "vcs", "url": "http://github.com/hglattergotz/json-schema" } ],
Dependencies
- JsonPretty A Json pretty printer by Cam Spiers
- JsonSchema A Json Schema validation library by Justin Rainbow
Usage
Encode
<?php $data = array( 'field' => 'value' ); $jsonString = Json::encode($data);
Decode from string
Decode the contents of $jsonString as an associative array.
<?php $data = Json::decode($jsonString, true);
Decode from file
Decode the contents of the file at $path as an associative array.
<?php $data = Json::decode($path, true);
Pretty print
Note that the source can either be a JSON string or an array. The call below uses the default indentation of 2 spaces. To use a different indentation pass it as the second parameter.
<?php $prettyJson = Json::prettyPrint($data);
Error handling
Instead of having to call json_last_error() and evaluating the integer
response code the decode and encode methods throw an exception that contain
the message as well as the code.
<?php $invalidJson = '{'; try { $data = Json::decode($invalidJson); } catch (HGG\Json\Exception\RuntimeException $e) { printf("Error message: %s\n", $e->getMessage()); printf("Error code: %d\n", $e->getCode()); }
The code above example will output:
Error message: JSON Error - Syntax error, malformed JSON
Error code: 4
统计信息
- 总下载量: 94
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 2
- 点击次数: 1
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2013-11-24