Typed models from real data

Turn a JSON sample into code you can start from

Paste one or more representative JSON values, choose a target, and generate nested models locally. Review inferred optional fields and mixed types, then copy, export, or open the generated result as a new document.

  • 11 targets
  • Multiple samples
  • Nested models
  • Local generation
JSON to Code Generator showing deployment JSON beside generated TypeScript interfaces
Two deployment-event samples produce reusable TypeScript interfaces with nested actor and metrics types.
Process

Use representative data, not an invented model

The quality of an inferred model depends on the samples. Give the generator enough real variation to distinguish required fields, optional fields, arrays, nested objects, integers, decimals, booleans, and nulls.

1

Load the sample

Start with the current JSON document, paste another sample, or combine several examples in an array.

2

Name and choose

Set the root type name, select a language or JSON Schema, and optionally make every property optional.

3

Review the result

Inspect the generation summary, copy the output, export it with the correct extension, or open it in CodePrettify.

Sample inference

Why more than one object matters

The second deployment contains rollbackUrl while the first does not. That variation gives the generator evidence that the property should be optional.

Input sample

Two deployment events

Nested objects, arrays, timestamps, integers, booleans, and one conditionally present field.

[
  {
    "id": "deploy_7fb8c0e3",
    "service": "api-gateway",
    "actor": { "id": 42, "automated": true },
    "regions": ["eu-north-1"],
    "metrics": { "durationMs": 8421, "warnings": 0 }
  },
  {
    "id": "deploy_91ca34d2",
    "service": "formatter-worker",
    "rollbackUrl": "https://deploy.example/rollback/91ca"
  }
]
TypeScript result

The optional field is explicit

Property names and nested shapes stay tied to the JSON while generated types use the selected language conventions.

export interface DeploymentEventItem {
  id: string;
  service: string;
  actor: Actor;
  regions: string[];
  metrics: Metrics;
  rollbackUrl?: string;
}

export type DeploymentEvent =
  DeploymentEventItem[];
Hands-on tutorial

Generate an honest model from varied order samples

The goal is not merely to produce code. It is to give the generator enough evidence to describe required, optional, nullable, nested, and repeated values without hiding uncertainty.

  1. Open the generator from the document or as a general tool

    With JSON already open, choose More Actions → General tools → JSON to Code Generator and select Use document. You can also launch the generator first and paste a sample. Using the document avoids an extra copy and keeps the source nearby for verification.

  2. Supply variation deliberately

    Use an array of representative objects. This small practice sample proves that discountCode is conditional, shippedAt can be null, and tags contains strings even though one array is empty.

    [
      {
        "id": 1001,
        "status": "processing",
        "discountCode": "SUMMER",
        "shippedAt": null,
        "tags": ["priority"]
      },
      {
        "id": 1002,
        "status": "shipped",
        "shippedAt": "2026-07-24T14:32:00Z",
        "tags": []
      }
    ]
  3. Name the domain concept, not the transport detail

    Set a root name such as Order, not Response or Data, unless the wrapper itself is the model you intend to keep. For package- or namespace-based targets, enter the destination used by your project so generated declarations arrive in the right context.

  4. Generate the first target and read the evidence

    Choose TypeScript and generate. Confirm that the root remains an array, discountCode is optional because it is absent from one record, shippedAt permits null, and tags is a string array. If a result surprises you, inspect the input evidence before editing the generated code.

  5. Switch targets without changing the sample

    Choose Python + Pydantic, Zod, C#, or another target. Compare how each ecosystem expresses the same optional and nullable evidence. The syntax changes, but the inferred shape should remain consistent unless a language lacks a direct equivalent and must use a safer general type.

  6. Read warnings as missing knowledge

    An empty array in every sample cannot reveal an element type. Genuinely mixed values may require a union or general type. A property seen in only one record becomes optional. Add another trustworthy sample when you have evidence; do not add invented values simply to silence a warning.

  7. Copy or open the result, then verify it in the project

    Copy, export with the suggested extension, or open the generated output as a CodePrettify document. Compile it, run your serializer, and test representative payloads. Generated models are a starting point: domain validation, naming conventions, precision, date parsing, and framework configuration still belong to your application.

Practice: change one piece of evidence at a time

Duplicate the sample and make one controlled change, then regenerate. This is the fastest way to learn how inference reacts.

  • Add a third object without shippedAt and observe optional plus nullable behavior.
  • Add a third record with a decimal total and inspect the numeric type.
  • Add a numeric priority beside a string priority and inspect the mixed-value warning or union.
  • Use a key such as user-id and inspect the target’s alias or field mapping.
  • Make every tags array empty and read the unknown-element warning.
  • Generate JSON Schema and compare its required list with the typed target.
Targets

Switch languages without changing the sample

The same inference model drives every output target. That makes it easy to compare how TypeScript, validation schemas, backend models, systems languages, and mobile types express the same data.

Generated TypeScript interfaces beside a JSON deployment sample
TypeScript preserves nested interfaces and marks evidence-based optional properties.
Generated Python Pydantic models beside the same JSON deployment sample
Python + Pydantic uses BaseModel, aliases JSON property names, and exposes optional values.

Web

  • TypeScript interfaces and aliases
  • TypeScript + Zod runtime schemas
  • JSON Schema Draft 2020-12

Application

  • C# models
  • Java + Jackson
  • Kotlin + kotlinx.serialization
  • Python + Pydantic

Systems and mobile

  • Go structs
  • Rust + Serde
  • Swift + Codable
  • Dart + json_serializable
Inference decisions

What the generator looks for

Required versus optional

A property missing from any object sample becomes optional. You can also force every generated property to be optional.

Numbers and nulls

Whole and fractional values inform integer or number types. Null participates in a nullable or union type instead of being discarded.

Nested object reuse

Repeated object shapes become named definitions so generated output is easier to read and maintain.

Reserved identifiers

Language-specific reserved words and invalid identifiers are renamed or represented through aliases where the target supports them.

Mixed values

When samples disagree, the generator uses a compatible union or general type rather than pretending every value has one shape.

Safe limits

Input size, output size, depth, and inspected values are capped so a pathological sample cannot lock the interface indefinitely.

Generation happens locally.

The JSON sample is not sent to an inference API. This is deterministic model generation performed by the installed CodePrettify runtime.

Review lesson

Know what to accept, change, and verify

Inference describes observed JSON; it cannot know the complete business contract. Review the generated result by separating facts proved by the sample from rules that only your application knows.

Generated decisionWhy it happenedWhat you should verify
Required propertyThe property appeared in every object sample.Can the real API omit it in errors, partial responses, or older versions?
Optional propertyAt least one sampled object omitted it, or “all optional” was selected.Is absence different from an explicit null in your domain?
Nullable or union typeThe sample contained null or incompatible value kinds.Should the application accept every observed type, or reject inconsistent source data?
Integer versus general numberObserved values were whole numbers or included fractions.Could IDs exceed safe numeric precision, and should monetary values use a decimal type?
Nested model nameA repeated object shape became a reusable declaration.Does the generated name match your domain vocabulary and project conventions?
Aliased propertyThe JSON key was invalid or reserved in the target language.Does the serializer annotation preserve the exact source key during round trips?

Too many optional properties

Check whether unrelated object shapes were placed in the same array or whether sparse partial responses were mixed with full records. Separate different domain types when they should not be merged.

An array has an unknown element type

At least one trustworthy sample needs a populated array. If no example exists, keep the safe unknown type and refine it from the API contract rather than guessing.

The root type looks awkward

Inspect whether the sample root is an array, a wrapper object, or the entity itself. Rename the root for the concept your code will use and keep transport wrappers only when they matter.

The code compiles but validation is weak

Type declarations do not automatically enforce runtime rules. Use Zod or JSON Schema when runtime validation is required, then add domain constraints the sample could not infer.

Learning outcome: you should be able to point to the sample evidence behind every optional, nullable, nested, array, and mixed-value decision—and identify which domain rules still require human review.

FAQ

JSON to code questions

Is the generated code production-ready?

It is a strong starting point inferred from the samples you provide. Review naming, domain constraints, validation rules, serialization settings, and optionality before treating it as a finished contract.

Can I generate from the JSON already open?

Yes. Choose “Use document” in the generator to load the current JSON without copying it manually.

How do I get better optional-field inference?

Use an array containing several representative objects, including examples where conditionally present fields are absent.

Can I generate a schema and validate the original?

Generate JSON Schema, open or copy it, then use CodePrettify’s JSON Schema Validator against the original document.

Related guides

Use the sample you already trust

Open a JSON payload, generate the target model locally, and keep the source and result inside the same developer workspace.