greenskies / json
An improved php json library
0.2.0
2019-03-08 00:04 UTC
Requires
- ext-json: *
- justinrainbow/json-schema: ^5.2
- karriere/json-decoder: ^2.2
- symfony/options-resolver: ^4.2
Requires (Dev)
- php-coveralls/php-coveralls: ^2.1
- phpunit/phpunit: ^7.0 | ^8.0
This package is auto-updated.
Last update: 2024-12-08 16:44:48 UTC
README
Greenskies Json
A PHP library to improve decoding - including schema validation and decoding to a class
It is basically a wrapper for:
- karriereat/json-decoder
- justinrainbow/json-schema With a little syntatic sugar and exceptions, even on PHP < 7.3
Installation
composer require greenskies/json
Decoding
To decode a json string simply pass the string to Json::Decode()
This will return a standard object
$jsonString = '{"good":true}'; $decoded = Json::Decode($jsonString); // $decoded->good = true
$jsonString = '{"good":true}'; $options = [ Json::ASSOCIATIVE => true, ]; $decoded = Json::Decode($jsonString, $options); // $decoded['good'] = true
Schema Validation
$jsonString = '{"processRefund": "true", "refundAmount": "17"}' $schema = (object) [ "type"=>"object", "properties"=>(object)[ "processRefund"=>(object)[ "type"=>"boolean" ], "refundAmount"=>(object)[ "type"=>"number" ] ] ]; $options = [ Json::VALIDATOR => [ Json::JSON_SCHEMA => $schema, Json::CONSTRAINTS => Constraint::CHECK_MODE_COERCE_TYPES, ], ]; $decoded = Json::Decode($jsonString, $options);
For further instructions visit justinrainbow/json-schema
Decode to a class
$jsonString = '{"id": 1, "name": "John Doe"}'; $options = [ Json::DECODER => [ Json::CLASS_NAME => Person::class, ], ]; $decoded = Json::Decode($jsonString, $options);
Decode Multiple
$jsonString = '[{"id": 1, "name": "John Doe"}, {"id": 2, "name": "Jane Doe"}]'; $options = [ Json::DECODER => [ Json::CLASS_NAME => Person::class, Json::DECODE_MULTIPLE => true, ], ]; $personArray = Json::Decode($jsonString, $options);
For further instructions visit karriereat/json-decoder