Simple packages are focused on being straightforward, clean, concise solutions for common needs.
Json is a convenience wrapper for json encoding/decoding. Its main purpose is to set sane defaults and make managing encoding/decoding options easy.
Requires php 7.3 or later.
Recommended installation method is via Composer: simply composer require php-enspired/simple-json
.
By default, objects are decoded as associative arrays and big integers are decoded as strings (rather than converting them to float).
When encoding data, big integers are encoded as strings, "zero" fractions are preserved (rather then encoding them as integers), and slashes and unicode characters are not escaped. To prevent unexpected/unpredictable results, objects will not be encoded unless they are stdClass
or implement JsonSerializable
.
Both encoding and decoding throw on error; this cannot be overridden.
Json defines some constants for sets of encode/decode options. As a convenience, these options are also settable via static factory methods.
ENCODE_ASCII
: default encoding options, but unsetsJSON_UNESCAPED_UNICODE
.ENCODE_HEX
: all of theJSON_HEX_*
options.ENCODE_HTML
: default encoding options, but unsetsJSON_UNESCAPED_SLASHES
.ENCODE_PRETTY
: default encoding options, and also setsJSON_PRETTY_PRINT
.
<?php
use AT\Simple\Json\Json;
// example data
$a = ["foo" => "one", "bar" => "two"];
// basic encoding and decoding (note $assoc = true is the default mode)
$json = Json::default();
$j = $json->encode($a); // {"foo":"one","bar":"two"}
$a === $json->decode($j); // bool (true)
// special options - e.g., "pretty" formatting
Json::pretty()->encode($a);
/*
{
"foo": "one",
"bar": "two"
}
*/
// decoding objects as stdClass
(new Json([Json::DECODE_ASOOC => false]))->decode($j);
/*
object(stdClass)#1 (2) {
["foo"]=>
string(3) "one"
["bar"]=>
string(3) "two"
}
*/
- Getting Started (It's Simple)
- Constructor and Factory Methods
- Encoding and Decoding
- Managing Options
- Handling Errors
I'm on Freenode at #php-enspired
, or open an issue on github. Feedback is welcomed.