I copied an API response into a blank file and started a TypeScript interface by hand. The payload was a list of two people. Each object had an id, a name, a role, and a meta object with an active flag. I typed the fields from the first person and assumed the second person used the same keys. The JSON converter at https://kepttools.com/json-converter makes that rule visible. Paste the text. It runs in the browser and drafts the interface from the first object only. The same paste can also become a PHP DTO, a Laravel array, or CSV. The sample below is the array the page fills, and the TypeScript is the converter's output for that text.
[
{"id": 1, "name": "Ada", "role": "engineer", "meta": {"active": true}},
{"id": 2, "name": "Linus", "role": "founder", "meta": {"active": false}}
]
TypeScript stops at Ada. Linus does not add a field. meta becomes its own interface because the value is an object. The root name is Root.
export interface Root {
id: number;
name: string;
role: string;
meta: Meta;
}
export interface Meta {
active: boolean;
}
The PHP DTO is drafted from that same first object. The class is always named DataTransferObject. There is no child class. meta is public array $meta, and the constructor copies $data['meta'] through as an array. Laravel still walks the whole array, so both people remain and meta stays nested. CSV keeps the top-level keys and writes meta as one cell, with the inner quotes doubled:
id,name,role,meta
1,Ada,engineer,"{""active"":true}"
2,Linus,founder,"{""active"":false}"
TypeScript and the PHP DTO are drafted from the first object in an array. CSV keeps top-level keys only, and a nested object becomes one cell. Invalid JSON shows the parse error and leaves the output empty. { produces Expected property name or '}' in JSON at position 1 (line 1 column 2). The output box is cleared.
Before you save the draft, read the second object. A key that exists only there will not appear on the interface or the PHP class. Put that key on the object you convert, or add the property yourself. Rename DataTransferObject before you ship the class. A missing key is assigned with ?? null, including on a property declared public int $id.
The full guide, with the FAQ and the converter: https://kepttools.com/guides/json-to-typescript-php-dto-laravel
Top comments (0)