go-supertools
Developer & Data Tools

JSON to PHP Class Converter

Generate PHP 8 classes with typed properties from sample JSON.

Runs in your browser Your input never leaves your device.

0 characters | 0 words

Report a problem with this tool

About this tool

Paste a sample of your JSON and get PHP 8 classes: one class per object shape, with typed public properties through constructor promotion, ?type for values that may be missing or null, union types for mixed values, and docblocks such as @var Item[] that tell IDEs and static analysers what is inside an array. Each class has a fromArray method that builds the object from json_decode($json, true), including nested objects and lists of objects, so you can write Root::fromArray(json_decode($json, true)). Required properties come first because PHP requires parameters with defaults to come last. The shape is inferred from your sample: objects become named types, lists become list types, a key that is missing from some items of a list becomes optional, numbers without a fraction become integers (a list that mixes 1 and 2.5 is decimal), and a value that is sometimes one type and sometimes another becomes a union or a general type. The same shape in two places shares one type. Keys that are not valid names, such as 'user name', are converted and the original key is kept. We checked the output by running it with PHP 8.2: the code is syntax-checked and, for 37 samples with awkward key names and reserved words, objects were built from the data and every value was compared with the original. The generated code needs PHP 8.1 or later. Your JSON is processed in your browser and never uploaded. A JSON number such as 10.0 or 1e3 is read as a whole number, because the sample loses how it was written; tick Treat all numbers as decimals if your values can have a fraction.

How to use it

  1. Paste a sample of your JSON, a longer or more varied sample gives a better result.
  2. Set the name of the top-level type, and the options.
  3. Copy the code into your project.
  4. Adjust names and types that the sample could not tell, such as dates in strings.

Common problems

A property has the wrong type
The sample did not show the real range of values. Use a larger sample, or edit the type.
A key with a space or dash
It is converted to a camelCase property name (user name becomes userName), and fromArray reads the original key.
I need to convert the object back to JSON
Add a toArray method or implement JsonSerializable; the generator only reads data in.