Skip to content

JSON to MobX State Tree Models Converter — Numio

Converts a JSON snapshot into a MobX-State-Tree model definition, const myModel = t.model({...}). Objects become t.model, arrays t.array(...) built from all items, and keys that are missing or null in some items t.maybe or t.maybeNull.

Bootstrapping a store model from an existing API response or saved snapshot.

JSON

MobX-State-Tree Model

When to use it

  • Bootstrapping a store model from an existing API response or saved snapshot.
  • Moving plain observable state to MobX-State-Tree without writing every types.* call by hand.

How to use

  1. Paste a JSON snapshot of your store state.
  2. Review the t.model({...}) output; arrays of objects contain one inline t.model merged from all items.
  3. Copy it, add import { types as t } from "mobx-state-tree", then add identifiers, actions and views.

JSON snapshot

{
  "filter": "all",
  "selectedId": null,
  "todos": [
    { "id": 1, "title": "Write docs", "done": false, "tags": ["work"] },
    { "id": 2, "title": "Ship", "done": true, "dueAt": null }
  ]
}

MobX-State-Tree model

const myModel = t.model({
  filter: t.string,
  selectedId: t.frozen(),
  todos: t.array(
    t.model({
      id: t.number,
      title: t.string,
      done: t.boolean,
      tags: t.maybe(t.array(t.string)),
      dueAt: t.maybe(t.frozen()),
    }),
  ),
})

Details and limitations

Runs in a browser Web Worker; nothing is uploaded. The output is formatted with Prettier.

null next to a real value gives t.maybeNull(type); a value that is only null, and the items of an empty array, become t.frozen(), which accepts any serialisable value.

Keys missing from some array items become t.maybe(...). Mixed-type arrays use t.union, such as t.array(t.union(t.number, t.string)).

IDs are not detected as types.identifier, and no t.optional defaults, actions or views are generated.

FAQ

Can the root of the JSON be an array?

Yes. The result becomes t.array(t.model({...})) with the keys of all elements merged; keys missing from some elements are wrapped in t.maybe.

Why is my id field t.number and not an identifier?

The converter only looks at value types. Change it to t.identifier or t.identifierNumber if you need references or reconciliation by id.

Can I include functions in the input?

Input that is not valid JSON is parsed as a JavaScript object literal instead, so function expressions become t.frozen. In that mode only the first item of each array is used, so JSON input is recommended.

Specifications and references