php-enspired/simple-json

Convenience wrapper for json encoding/decoding.

2.0 2021-04-01 02:59 UTC

This package is auto-updated.

Last update: 2024-04-29 04:39:45 UTC


README

it's simple: json

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.

dependencies

Requires php 7.3 or later.

installation

Recommended installation method is via Composer: simply composer require php-enspired/simple-json.

basic usage

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 unsets JSON_UNESCAPED_UNICODE.
  • ENCODE_HEX: all of the JSON_HEX_* options.
  • ENCODE_HTML: default encoding options, but unsets JSON_UNESCAPED_SLASHES.
  • ENCODE_PRETTY: default encoding options, and also sets JSON_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"
}
*/

docs

contributing or getting help

I'm on Freenode at #php-enspired, or open an issue on github. Feedback is welcomed.