CodeGym /Cursos /Go SELF /Versioning the JSON format — {version, data}

Versioning the JSON format — {version, data}

Go SELF
Nível 46, Lição 3
Disponível

1. Why version a JSON format

When you are just starting to write a program, the data format seems eternal: what could possibly change in tasks? And then you suddenly decide that title should be renamed to text, or that the field done should become status: "done"|"todo", or that identifiers must now be strings. And then it turns out that “yesterday’s” data has suddenly become “unreadable archaeology”.

Versioning is a way to tell yourself, and the program: “Yes, the format changes, and that is normal.” We are not trying to predict the future. We simply add an explicit switch that the code uses to choose how to read the document. This greatly reduces the chance that your users will send you files with the phrase “nothing works”, while you will be opening them in a hex editor and crying.

Imagine our training app — a simple task manager. Let the domain model, the way we think about a task inside the program, look like this:

package main

type Task struct {
	ID    int
	Title string
	Done  bool
}

So far, so good. But the storage format is an external contract. And external contracts are better made so that they survive your “creative phase” of project development.

2. Envelope { "version": N, "data": ... }

To make the format changeable, we do not try to store “every field under the sun” at once. We create an envelope with a version number and a payload. The most minimal and readable pattern looks like this:

{
  "version": 2,
  "data": { ... }
}

The trick is that we read the version first, and only then decide what to decode data into. And that is where json.RawMessage becomes the perfect tool: it keeps a chunk of JSON “as is”, without forcing us to choose a structure too early.

In Go, such an envelope can be described like this:

package main

import "encoding/json"

type Envelope struct {
	Version int             `json:"version"`
	Data    json.RawMessage `json:"data"`
}

json.RawMessage is basically []byte, but with an “official meaning”: “this is a valid JSON fragment, I will just parse it later.”

3. DTO and domain: migration as a separate function

It is very easy to do things “messily”: you read JSON from the old version and immediately start writing if version == 1 { ... } else { ... }, spreading conversion rules throughout the code. That is how the “version soup” is usually born, and it becomes scary to touch later.

It is better to keep one simple idea in mind: the domain model (Task) is what the program works with. And the structures for JSON are DTOs (data transfer objects), that is, data shapes “for transfer/storage”.

So we will define two DTO versions and make it possible to turn any version into the domain model.

Suppose that in version 1 the field was called text, and in version 2 we decided to rename it to title.

package main

type TaskV1 struct {
	ID   int    `json:"id"`
	Text string `json:"text"`
	Done bool   `json:"done"`
}

type TaskV2 struct {
	ID    int    `json:"id"`
	Title string `json:"title"`
	Done  bool   `json:"done"`
}

The migration then becomes as boring as possible, which is a compliment when it comes to migrations:

package main

func (t TaskV1) ToDomain() Task {
	return Task{
		ID:    t.ID,
		Title: t.Text,
		Done:  t.Done,
	}
}

And a separate function “from the new version” can exist too, although it is usually trivial:

package main

func (t TaskV2) ToDomain() Task {
	return Task{ID: t.ID, Title: t.Title, Done: t.Done}
}

4. Compatibility: read all versions, write only the current one

There is one very practical principle that makes life easier: the program must be able to read old data (otherwise you break users), but it must write only one current format, otherwise you will start creating a zoo.

Let us agree that the current version is 2:

package main

const CurrentVersion = 2

This matters not only for writing, but also so that the code is “self-documenting”: when you see CurrentVersion, you understand that this is the center of your format’s world.

5. Two-step reading: Envelope → data by version

Below is the core of the whole lecture: how to read {version, data}.

First we decode the envelope, getting env.Version and env.Data. Then we do a switch on the version and decode env.Data into the structure for the specific version.

package main

import (
	"encoding/json"
	"fmt"
)

func decodeTasksFromData(version int, data []byte) ([]Task, error) {
	switch version {
	case 1:
		var v1 []TaskV1
		if err := json.Unmarshal(data, &v1); err != nil {
			return nil, err
		}

		out := make([]Task, 0, len(v1))
		for _, t := range v1 {
			out = append(out, t.ToDomain())
		}
		return out, nil

	case 2:
		var v2 []TaskV2
		if err := json.Unmarshal(data, &v2); err != nil {
			return nil, err
		}

		out := make([]Task, 0, len(v2))
		for _, t := range v2 {
			out = append(out, t.ToDomain())
		}
		return out, nil

	default:
		return nil, fmt.Errorf("unsupported version %d", version)
	}
}

Please note: migration is not “JSON magic”. It is ordinary Go code: loops, structures, assignments. And that is the strength of it: you fully control what counts as a correct transfer of meaning.

6. Strict envelope reading: unknown fields and trailing data

Now comes an important point that people usually understand only after a couple of unpleasant bugs. If your format is a contract, then the envelope must be strict. Otherwise someone will send:

{"version":2,"data":[...],"verison":999}

and you will be wondering why nothing works (spoiler: a typo in version).

We can use json.Decoder + DisallowUnknownFields() for the envelope and additionally check that there is exactly one JSON document in the input.

Let us write a small helper. Yes, it is a bit “boilerplate”, but it is a good template.

package main

import (
	"encoding/json"
	"fmt"
	"io"
)

func decodeOneStrict(r io.Reader, v any) error {
	dec := json.NewDecoder(r)
	dec.DisallowUnknownFields()

	if err := dec.Decode(v); err != nil {
		return err
	}

	if err := dec.Decode(&struct{}{}); err != io.EOF {
		if err == nil {
			return fmt.Errorf("unexpected extra JSON value")
		}
		return fmt.Errorf("trailing data: %w", err)
	}
	return nil
}

It is useful here to remember the Go philosophy: errors are values, and we check them explicitly; this is a normal part of program flow control. This style of error handling and “adding context” through fmt.Errorf(..., %w) is one of the basic Go patterns.

7. Reading tasks: ReadTasks(r io.Reader)

Now let us put everything into one function that reads tasks from io.Reader. This is convenient: you can apply it to a file, to the network, to stdin, to strings.NewReader, to bytes.Buffer — to anything.

package main

import (
	"fmt"
	"io"
)

func ReadTasks(r io.Reader) ([]Task, error) {
	var env Envelope
	if err := decodeOneStrict(r, &env); err != nil {
		return nil, fmt.Errorf("decode envelope: %w", err)
	}

	tasks, err := decodeTasksFromData(env.Version, env.Data)
	if err != nil {
		return nil, fmt.Errorf("decode tasks v%d: %w", env.Version, err)
	}
	return tasks, nil
}

Pay attention to the error text: we added context decode envelope and decode tasks vN. This helps when an error “bubbles up” and you want to understand at which step everything broke. In general, Go encourages exactly this approach to errors: not only “what broke”, but also “in which action”.

8. Writing tasks: WriteTasks(w io.Writer, tasks []Task)

Our reading already supports several versions. We write only one current version so that we do not multiply formats.

We need to take domain Task, turn it into TaskV2, wrap it in an envelope, and write it through json.Encoder. For beauty, you can also use SetIndent, but that is optional.

package main

func toV2(tasks []Task) []TaskV2 {
	out := make([]TaskV2, 0, len(tasks))
	for _, t := range tasks {
		out = append(out, TaskV2{ID: t.ID, Title: t.Title, Done: t.Done})
	}
	return out
}

And now the write:

package main

import (
	"encoding/json"
	"io"
)

func WriteTasks(w io.Writer, tasks []Task) error {
	payload := toV2(tasks)

	env := Envelope{
		Version: CurrentVersion,
		Data:    mustJSON(payload),
	}

	enc := json.NewEncoder(w)
	enc.SetIndent("", "  ")
	return enc.Encode(env)
}

There is one “trick” here: data is json.RawMessage, while payload is a structure. That means we need to turn payload into JSON bytes once. Let us make a small helper, but carefully: in real code, it is better to return an error instead of panicking. For the lecture, we will show a version without panics.

package main

import "encoding/json"

func mustJSON(v any) json.RawMessage {
	b, _ := json.Marshal(v)
	return b
}

If you thought, “this is not allowed, the error is ignored” — you are right. We are just focusing on the format version right now. In a real application, use json.Marshal with error checking and a proper return error.

9. Examples and testing

What it looks like in JSON

It is useful to see with your own eyes what exactly changes.

Version 1 (old format, field text):

{
  "version": 1,
  "data": [
    { "id": 1, "text": "buy bread", "done": false }
  ]
}

Version 2 (current format, field title):

{
  "version": 2,
  "data": [
    { "id": 1, "title": "buy bread", "done": false }
  ]
}

For the user, this is almost the same thing. For your code, these are fundamentally different structures. And versioning makes it possible to support both variants honestly and transparently.

Mini diagram of the process

When you read a versioned document, the mental process should be this:

flowchart TD
    A[io.Reader] --> B[Decode Envelope]
    B --> C{version}
    C -->|1| D["Unmarshal data as []TaskV1"]
    C -->|2| E["Unmarshal data as []TaskV2"]
    D --> F["map to []Task domain"]
    E --> F["map to []Task domain"]
    F --> G[then work in code only with domain Task]

The key gain is this: after migration into the domain model, the rest of the code should not know what JSON format there used to be at all. This drastically reduces the number of places where you can make a mistake.

Table of format changes

Sometimes it is useful to keep a very short “format history” right in the code or nearby. Even if you are the only developer, after a month you already will not remember why you renamed text to title.

Version data structure Difference
1
[]TaskV1
field text
2
[]TaskV2
field title

This is not so much a “technical table” as a way to avoid turning life into a “guess the past” quest.

How to test migration without files

It is very convenient that our functions work with io.Reader/io.Writer. That means the test scenario can be assembled right in memory using strings.NewReader and bytes.Buffer.

An example of “read the old version and get the domain model”:

package main

import (
	"fmt"
	"strings"
)

func demoReadV1() {
	input := `{"version":1,"data":[{"id":7,"text":"learn go","done":true}]}`
	tasks, err := ReadTasks(strings.NewReader(input))
	fmt.Println(tasks, err) // [{7 learn go true}] <nil>
}

And an example of “write in the current version”:

package main

import (
	"bytes"
	"fmt"
)

func demoWriteV2() {
	var buf bytes.Buffer
	_ = WriteTasks(&buf, []Task{{ID: 1, Title: "sleep", Done: false}})
	fmt.Println(buf.String()) // JSON envelope version 2 (pretty, with indentation)
}

The advantage of this approach is that you can run the migration a thousand times per second without depending on disk, paths, permissions, and other “joys of adult life”.

10. Typical mistakes

Mistake #1: decode data into the current structure before reading version.
This is the most common slip: you want to “just read the tasks”, and your hand reaches for json.Unmarshal straight into []TaskV2. As a result, version 1 either fails or, worse, is read partially if the fields “happen to match”. The correct discipline is always Envelope first, then a switch by version.

Mistake #2: spreading migration through the business logic.
If if version == 1 starts appearing in code that is “about tasks” (search, filters, display), you gradually turn the project into a museum of formats. Migration should happen at the data-reading boundary: read → migrate → then only the domain model.

Mistake #3: trying to support many write formats.
Sometimes it seems logical: “if we already read v1/v2, let’s also be able to write v1/v2.” Usually this leads to you trapping yourself: options appear, branches appear, tests appear, and nobody understands which format is the “main” one. Much simpler: read many, write one current format.

Mistake #4: not treating an unknown version as an error.
If version 999 arrives, that is not “let’s try to read it as v2”. It is a signal that the data is from the future or the format is broken. An unknown version must produce an explicit error, otherwise you will get strange states and broken data without a clear reason.

Mistake #5: making the envelope non-strict and silently swallowing typos.
If you do not enable DisallowUnknownFields() at least for the envelope, then a typo in the key ("verison") may go unnoticed, and Version will become 0. Then you will get “unsupported version 0” and spend a long time looking for who stole the one and the two. Strict envelope parsing saves a lot of debugging time.

1
Tarefa
Go SELF, nível 46, lição 3
Bloqueado
Versão do envelope
Versão do envelope
1
Tarefa
Go SELF, nível 46, lição 3
Bloqueado
Migração de modelos
Migração de modelos
1
Tarefa
Go SELF, nível 46, lição 3
Bloqueado
Leitura de versões
Leitura de versões
1
Tarefa
Go SELF, nível 46, lição 3
Bloqueado
Atualização do envelope
Atualização do envelope
Comentários
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION