Download the PHP package diamond-dove/simple-json without Composer
On this page you can find all versions of the php package diamond-dove/simple-json. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download diamond-dove/simple-json
More information about diamond-dove/simple-json
Files in diamond-dove/simple-json
Package simple-json
Short Description Read and write big JSON files
License MIT
Homepage https://github.com/diamond-dove/simple-json
Informations about the package simple-json
Simple JSON File Reader and Writer
This package makes it easy to read and write simple JSON files. It uses generators to minimize memory usage, even when dealing with large files.
⭐ Enjoying this package? If it saves you time, please consider giving it a star on GitHub — it helps other developers discover it and motivates continued work. Thank you!
Here is an example of how to read a JSON file:
Requirements
- PHP 8.4 or higher
Installation
You can install the package using composer:
Usage
Reading a JSON
Suppose you have a JSON file with the following content:
To read this file in PHP, you can do the following:
Working with LazyCollections
get will return an instance of Illuminate\Support\LazyCollection. This class is part of the Laravel framework. Behind the scenes generators are used, so memory usage will be low, even for large files.
You'll find a list of methods you can use on a LazyCollection in the Laravel documentation.
Here's a quick, silly example where we only want to process rows that have a first_name that contains more than 5 characters. You'll find a list of methods you can use on a LazyCollection in the Laravel documentation.
Here's a quick, silly example where we only want to process elements that have a first_name that contains more than 5 characters.
Reading from a string or a stream
You don't have to read from a file. If you already have the JSON in a string, or in an open stream resource, you can read from it directly:
Writing files
To write a JSON file, you can use the following code:
The file at pathToJson will contain:
You can also use:
In-memory JSON toolkit
Besides streaming whole files, the package ships a small, framework-agnostic toolkit
for working with a single JSON document in memory: safe parsing, dot-path access with
strict typed extraction, and validation — all via the static Json facade, with zero
extra dependencies.
Safe parsing & typed access
Json::parse() decodes with JSON_THROW_ON_ERROR and, on malformed JSON, throws a
DiamondDove\SimpleJson\Exceptions\InvalidJsonException (the native JsonException is
chained as $previous) — so you never have to second-guess json_decode()'s ambiguous
null return. Use Json::tryParse() for a null-on-failure variant that never throws.
path() walks dot-notation (case-sensitive) and returns another accessor. The typed
terminals come in three flavours:
Terminals are strict — no silent coercion: int requires a real integer, float
widens an integer to float (5 → 5.0), bool rejects 0/1. The full set is
string, int, float, bool, array, each with *Or($default) and *OrNull()
variants.
Limitation:
path()uses dot-notation; a JSON key that contains a literal dot (e.g."weird.key") is matched as a whole key first by the underlying resolver, while a genuinely nested{"weird":{"key":...}}is what dot-segmentation targets — avoid literal dots in keys you intend to traverse.
Validation
Json::validate() checks a JSON document against Laravel-style rules using a tiny
in-house engine — no illuminate/validation and no other new dependency. Rules are
written as pipe strings or arrays, and fields are addressed with the same dot-notation as
path().
Supported rules: required, nullable, string, int, numeric, bool, array,
email, min, max, between, in, regex. Type rules are strict (consistent
with the accessor): int/numeric reject numeric strings, bool rejects 0/1.
min/max/between are inclusive and type-aware (number magnitude, string length, or
array count). An unknown rule or a missing rule parameter throws \InvalidArgumentException
(it's a programming error, not a validation failure).
Mapping to typed objects (DTOs)
Json::map() hydrates a plain PHP class from a JSON string (or an already-decoded array)
using constructor property promotion — no setters, no reflection-written private
properties, and no heavy mapping dependency. It maps source keys to constructor
parameters by name, recurses into nested DTOs, hydrates backed enums, and maps lists of
DTOs via the #[ListOf] attribute.
Mapping is strict, mirroring the rest of the toolkit: a type mismatch, a missing
required parameter, or an invalid enum value throws a
DiamondDove\SimpleJson\Exceptions\JsonMappingException (which also implements the
JsonException marker, so a thrown DTO-constructor exception is wrapped and chained as
$previous). Extra source keys are ignored.
Because Json::map() also accepts a decoded array, it composes directly with the streaming
reader — hydrate every row of a huge file into typed objects without loading the whole file:
JSONPath queries (optional)
For queries that go beyond the core dot-notation path() — recursive descent,
wildcards, array slices, filter expressions — Json::query() wraps the
softcreatr/jsonpath package. It is an
optional dependency: the toolkit core stays dependency-free, and you only pull it in
if you need full JSONPath.
If the package is not installed, Json::query() throws a
DiamondDove\SimpleJson\Exceptions\MissingDependencyException whose message tells you
exactly what to install. An invalid JSONPath expression throws JsonQueryException, and
malformed JSON throws InvalidJsonException — all three implement the JsonException
marker, so you can catch them uniformly.
JSON Schema validation (optional)
When you already have a JSON Schema, Json::validateSchema() validates a document against
it by wrapping the optional opis/json-schema
package (multiple drafts). It complements the built-in rule engine.
Remote $refs are not fetched (no network access), so the validator is safe against
SSRF. A structurally invalid schema throws JsonSchemaException; a document that simply
doesn't conform is reported through the result (not an exception).
Advanced typed mapping (optional)
Json::map() covers plain DTOs. For advanced type signatures it can't express —
list<string>, int<0,100>, non-empty-string, shaped arrays, generics — Json::mapTo()
wraps the optional cuyz/valinor mapper.
Data that violates the signature throws JsonMappingException; an invalid signature is a
programming error and throws \InvalidArgumentException.
Testing
Changelog
Please see CHANGELOG for details on what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security
If you discover any security related issues, please email [email protected] instead of using the issue tracker.
Show your support
If this package is useful to you, please ⭐ star it on GitHub. It's the easiest way to support the project, helps others find it, and is genuinely appreciated.
Credits
- Fermin Perdomo
- All Contributors
License
The MIT License (MIT). Please see License File for more information.