Skip to content
phpgtPublic

About

Structured, type-safe, immutable JSON objects, with schema validation.

Topics

Resources

Security policy

Stars

1 star

Watchers

1 watching

Forks

Repository files navigation

Structured, type-safe, immutable JSON objects.

Built on top of PHP.Gt/DataObject, this repository adds JSON-specific compatibility. The main usage will be via the JSONObjectBuilder class that can be used to build a type of JSONObject from a JSON string or decoded JSON object (from json_decode).

The purpose of using these classes to represent decoded JSON data is to provide a type-safe, immutable interface to the enclosed data.


Build status Code quality Code coverage Current version PHP.Gt/Json documentation

The abstract JSONObject class extends the DataObject base class to represent the root element of a JSON object. In JSON, this may not necessarily be a key-value-pair object.

The following JSON strings can all be successfully decoded:

  • {"type": "key-value-pair"} - a typical key-value-pair object
  • [{"name": "first"}, {"name": "second"} - an array of objects
  • 0 - an integer
  • 1.05 - a floating point
  • false - a boolean
  • "Today is going to be a good day" - a string
  • null - a null

Because of this, the base DataObject would be unable to represent the different types of scalar value in a type-safe way. The JSONObjectBuilder class returns a new instance of the abstract JSONObject class which is one of the following types:

  • JSONKvpObject - identical features to DataObject with type-safe getters for its keys
  • JSONPrimitive - a representation of the primitive value, further broken down into types JSONArrayPrimitive, JSONBoolPrimitive, JSONFloatPrimitive, JSONIntPrimitive, JSONNullPrimitive and JSONStringPrimitive.

Usage example

use GT\Json\JSONObjectBuilder;
use GT\Json\JSONKvpObject;
use GT\Json\JSONPrimitive\JSONPrimitive;

$response = file_get_contents("https://example.com/details.json");
$builder = new JSONObjectBuilder();
$jsonObject = $builder->fromJsonString($response);

if($jsonObject instanceof JSONKvpObject) {
	$id = $jsonObject->getInt("id");
}
elseif($jsonObject instanceof JSONPrimitive) {
	$id = $jsonObject->getPrimitiveValue();
}

echo "Requested ID is: $id";

Fetch API

Check out the PHP implementation of the Fetch API that uses this library to work with JSON endpoints asynchronously.

Root JSON arrays

Root arrays returned by JSONObjectBuilder::fromJsonString() support count() and foreach. Iterators preserve keys and values and remain independent during nested or repeated loops. Empty [] values remain JSON arrays. See the array documentation for examples.

Proudly sponsored by

JetBrains Open Source sponsorship program

JetBrains logo.

About

Structured, type-safe, immutable JSON objects, with schema validation.

Topics

Resources

Security policy

Stars

1 star

Watchers

1 watching

Forks

Releases

Sponsor this project

Used by

Contributors

Languages