ergebnis/json
Value object for representing valid JSON strings in PHP. Create Json instances from strings or files with strict validation and clear exceptions for invalid JSON, missing files, unreadable files, or non-JSON content. Install via Composer: ergebnis/json.
Install the package with composer require ergebnis/json, then start using the Ergebnis\Json\Json value object to represent validated JSON strings. The primary use case is to enforce that any JSON string in your domain (e.g., config payloads, API responses, event payloads) has already been validated and is structurally correct — preventing accidental use of malformed JSON later in your application. For example:
use Ergebnis\Json\Json;
$json = Json::fromString('{"status":"ok"}'); // safe: throws if invalid
echo $json->toString(); // '{"status":"ok"}'
Begin by reading the README.md, which provides all essential examples (from string, from file, exception types), and check the CHANGELOG for version-specific changes affecting PHP version support and APIs.
Typical workflows include:
Json\Json instead of string or mixed to enforce contract integrity at the type level.Json::fromFile() for safe, early validation of local JSON files (e.g., config.json, package.json), letting exceptions surface issues before runtime.Json\Json after checking Content-Type, then pass to domain services.Json::fromString($expectedJson) in unit tests to assert equality between actual and expected payloads (value objects implement strict identity and value semantics).You can extract associative arrays or objects for further processing using json_decode($json->toString(), true) when needed, but prefer keeping Json instances at boundaries and decoding only at the edges.
object (not array) is guaranteed (since v1.0.1), but when you manually decode after extraction, be explicit: json_decode($json->toString(), false) to avoid unintended behavior.NotJson, FileDoesNotExist, FileCanNotBeRead, and FileDoesNotContainJson let you differentiate failure modes cleanly. Don’t catch generic Exception — handle each case appropriately.json_encode, json_decode, or ergebnis/json-normalizer for richer workflows.Json implements __toString(), so echo $json just works, but in strcmp() or strict comparisons, rely on $json->toString() for consistency.fromString(), fromFile(), toString(), and __toString() exist — embrace the discipline of no optional parameters or default behavior. If you need normalization, use json-normalizer, which depends on this package.How can I help you explore Laravel packages today?