Skip to content

It's Simple: Json

Adrian edited this page Apr 1, 2021 · 4 revisions

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

<?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"
}
*/
Clone this wiki locally