| | |

SvelteKit Forms 09 ๐Ÿ“ Nested Objects, Arrays & dataType: ‘json’ โ€” Handling complex structured payloads

โฑ๏ธ Estimated read: 7 min | |

Real-world web applications rarely deal with flat, key-value pairs. They operate on complex, hierarchical models that include nested objects (like addresses) and dynamic arrays (like lists of skills or multi-line items). Standard HTML <form> inputs are inherently flat, and FormData treats everything as a string. Bridging the gap between raw FormData and complex JavaScript objects is a major challenge in modern development, often leading to brittle serialization logic.

Superforms solves this with the dataType: 'json' configuration, which allows the framework to automatically handle the serialization and deserialization of complex structures, enabling you to use Zod to define your entire object tree including arrays, deep objects, and boolean or numeric values.

Key point: When your Zod schema contains nested objects or arrays, you must set dataType: 'json' in your superForm configuration; this instructs the framework to serialize the form state into a JSON string before submission, circumventing the flat limitations of HTML FormData.


Why exists

The flat form limitation. Native FormData cannot represent nested structures or type-specific values (everything becomes a string). Without dataType: 'json', developers were forced to manually serialize data into hidden inputs, which is prone to errors.

The dynamic array challenge. In a form where a user can add or remove items (e.g., adding line items to an invoice), tracking the state of an arbitrary-length array and ensuring it maps to the correct schema index is notoriously difficult. Superforms provides proxy helpers for this.

The type-safety hurdle. When you deal with nested objects, it is easy for parts of the application to become “loosely typed” if the form state does not exactly match the serverโ€™s schema. dataType: 'json' ensures that the schema remains the source of truth from the input all the way to the database.

The complexity of boolean and numeric types. HTML inputs for numbers or checkboxes return strings or nothing at all, forcing developers to write redundant “coercion” code. By treating form state as a JSON object, you keep your data types pure.

The synchronization effort. Mapping complex client-side interactions to deep database updates requires an architectural bridge. Superforms acts as this bridge, allowing the server to receive a clean, nested structure ready for an ORM like Prisma or Drizzle.


a. Handling nested objects with Zod

By defining your Zod schema using .object() and nesting schemas within it, you create a structural contract. In your component, you bind to these deeply nested fields using dot notation, and Superforms manages the state updates recursively.

const schema = z.object({
  user: z.object({
    name: z.string(),
    contact: z.object({
      email: z.string().email(),
    })
  })
});

// Binding in Svelte 5
<input bind:value={$form.user.contact.email} />

Because dataType: 'json' is enabled, you don’t need to flatten your data. You can pass the nested structure directly from your server load function, and the reactive store will handle the path-specific updates even if the object tree is several levels deep.


b. Dynamic arrays with fieldProxy

For forms where users can add or remove items, Superforms provides the fieldProxy utility. This allows you to create a sub-store for a specific array or object, which is useful when passing specific parts of a large form to sub-components or when managing list-based UI operations.

const { form } = superForm(data.form, { dataType: 'json' });
const skills = fieldProxy(form, 'skills'); // Proxy for array

// Usage for adding items
function addSkill() {
  $skills = [...$skills, 'New Skill'];
}

The fieldProxy is essential for performance; it ensures that your child components only subscribe to the part of the form state they actually need, preventing unnecessary re-renders of the entire parent form when an array element is modified.


c. The power of dataType: ‘json’

The dataType: 'json' setting is the “magic” behind the scenes. It forces the form to serialize the entire object as a string inside a single superform field. On the server side, superValidate detects this JSON string and automatically parses it back into a JavaScript object before running validation.

// +page.server.ts
export const load = async () => {
  const form = await superValidate(zod(schema));
  return { form };
};

// Component config
const { form } = superForm(data.form, {
  dataType: 'json' // Required for nested structures
});

Without this, any array or deep object would be lost. With it, your FormData essentially acts as a container for your serialized application state. This is highly efficient and keeps your server-side actions clean, as they receive an object that already matches the expected Zod schema.


Complete Example Session

// ============================================
// PART 1: THE NESTED SCHEMA
// ============================================
const schema = z.object({
  title: z.string(),
  items: z.array(z.object({ name: z.string(), qty: z.number() }))
});

// ============================================
// PART 2: INITIALIZING
// ============================================
const { form } = superForm(data.form, { dataType: 'json' });
const itemsProxy = fieldProxy(form, 'items');

// ============================================
// PART 3: DYNAMIC ARRAY OPERATIONS
// ============================================
function addItem() {
  $itemsProxy = [...$itemsProxy, { name: '', qty: 0 }];
}

function removeItem(index) {
  $itemsProxy.splice(index, 1);
  $itemsProxy = $itemsProxy; // Trigger reactivity
}

// ============================================
// PART 4: COMPONENT UI
// ============================================
{#each $itemsProxy as item, i}
  <input bind:value={$itemsProxy[i].name} />
  <input type="number" bind:value={$itemsProxy[i].qty} />
  <button on:click={() => removeItem(i)}>Delete</button>
{/each}

This sequence builds a multi-line invoice-style form, demonstrating how to proxy nested arrays, handle dynamic addition/deletion, and preserve types via the JSON data configuration.


Quick Reference

Proxy Helpers

HelperPurpose
fieldProxySub-store for nested keys/arrays
arrayProxySpecialized store for array manipulation
dataType: 'json'Config for nested support

Data Type Benefits

BenefitDescription
Schema MirrorForm state = Database state
Type PurityNumbers/Booleans stay typed
SerializationAutomatic JSON conversion

Best Practices

โœ… Do This:

// Enable JSON mode for all complex forms
dataType: 'json'                                             // โœ…

// Use fieldProxy for array operations
const list = fieldProxy(form, 'items');                      // โœ…

// Deeply nest your schemas
z.object({ user: z.object({...}) })                          // โœ…

// Keep the form and schema in sync
// (Always update schema when adding fields)                  // โœ…

โŒ Don’t Do This:

// Don't rely on FormData for nested structures
// (It will break immediately)                               // โŒ

// Don't manual flatten data
// (Let dataType: 'json' handle it)                          // โŒ

// Don't ignore fieldProxy
// (Manual array slicing leads to bugs)                      // โŒ

Common Pitfalls

PitfallWhy It HappensFix
Nested data missingForgot dataType: 'json'Add to superForm config
Array reactivity lossManual array splicingUse fieldProxy or re-assign
Type coercion errorMissing z.coerceUse Zod’s coerce or native JSON
Flattened keysInconsistent schemaAlways use deep schema nesting

Real-World Examples

1. JSON Configuration

dataType: 'json'

2. Nested Field Proxy

const address = fieldProxy(form, 'user.address')

3. Adding Item

$items = [...$items, newItem]

4. Removing Item

$items.splice(i, 1); $items = $items

5. Numeric Input Handling

<input type="number" bind:value={$form.qty} />

6. Nested Validation

z.object({ data: z.object({ value: z.string() }) })

7. Array Proxy

const items = arrayProxy(form, 'items')

8. Server-side Action

const form = await superValidate(request, zod(schema))

9. Boolean Checkbox

<input type="checkbox" bind:checked={$form.active} />

10. Complex Form Binding

bind:value={$form.items[i].details.price}

Visual

The JSON Serialization Bridge

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  FORM STATE (Deep JS Object)         โ”‚
โ”‚             โ”‚                        โ”‚
โ”‚  dataType: 'json' (Serialize)        โ”‚
โ”‚             โ”‚                        โ”‚
โ”‚  FormData (Single JSON Field)        โ”‚
โ”‚             โ”‚                        โ”‚
โ”‚  Server (Parse) โ”€โ”€โ–บ Zod Validation   โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Proxying Architecture

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  PARENT STORE (Global)               โ”‚
โ”‚             โ”‚                        โ”‚
โ”‚  fieldProxy(key) โ”€โ”€โ–บ SUB-STORE       โ”‚
โ”‚             โ”‚                        โ”‚
โ”‚  Component A binds Sub-Store         โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Schema Mirroring

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  ZOD SCHEMA โ”€โ”€โ–บ FORM STATE           โ”‚
โ”‚  {                                   โ”‚
โ”‚    user: {                           โ”‚
โ”‚      email: z.string()               โ”‚
โ”‚    }                                 โ”‚
โ”‚  }                                   โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
dataType: 'json'Required for nested structures
fieldProxySub-store for arrays/objects
z.objectDeeply nested schema definition
Reactive bindingDot-notation $form.path.to.field

Key takeaways:

  • JSON is the key. Never try to work with complex structures in Superforms without enabling dataType: 'json'. It solves the fundamental limitation of FormData.
  • Use proxies for arrays. fieldProxy is the most reliable way to perform operations like adding or removing items from a list within a form.
  • Bind deeply. Because Superforms stores are proxies, you can simply use bind:value={$form.nested.field} and it just works, as long as the initial state contains that structure.
  • Maintain schema parity. Your schema defines your form state; if you add a nested field to your schema, make sure it is reflected in your initial load data.
  • Types matter. Because you are using Zod, your nested fields are type-checked at build time, preventing the classic “cannot read property of undefined” errors that plague nested forms.

Remember: Nested and dynamic forms are a step up in complexity, but Superforms handles the transition from flat to hierarchical data with elegance. By leveraging dataType: 'json' and the various proxy helpers, you can create forms that match the complexity of your data models without sacrificing the simplicity and reactivity that makes SvelteKit such a powerful framework.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!