Data conversion guides

Generate Go structs for JSON inventory records

·

Start with an API response that contains more than one inventory record. Shared and missing properties tell you where a Go value is sufficient and where a pointer or raw JSON is useful.

JSON to Go Struct

Inspect the inventory slice and its field tags

Choose Load example and Generate Go. The root Inventory type is a slice of InventoryItem. The first record's item-id of 9007199254740993 fits int64. Its ItemID field retains item-id as a JSON tag. Decode the original bytes with encoding/json.Unmarshal to preserve that integer.

Check the nested warehouse type. Aisle appears on just one record and becomes *int64 with omitempty. Note appears in both records, including as null in the first. It becomes *string without omitempty.

Go encoding/json packageGo specification, struct types

Keep mixed labels and check timestamp inference

Labels accepts a string and an integer across the sample records. The model uses []json.RawMessage. Decode the individual elements when the calling code knows which label kind it expects.

The dated updatedAt sample makes UpdatedAt a time.Time. Turn off Infer time.Time for RFC 3339 strings and generate again to keep its original text as a string. Choose JSON and DB tags when a separate database reader needs tag metadata. Check that its column names match your database.

Go encoding/json packageGo time.Time JSON unmarshaling

Select one record and compile the downloaded file

Enter /0 as Root JSON Pointer to generate a struct from the first array element. Only the first warehouse is observed, so Aisle disappears. Clear the pointer to infer from both records again.

Download models.go into your selected Go package. Compile it with your project and exercise json.Unmarshal, especially for missing keys, nulls and mixed labels. A Go pointer alone uses nil for both missing and null on a fresh struct.

Go encoding/json packageRFC 6901, JSON Pointer

Common questions

What happens to integers beyond int64?

They use json.Number so the original decimal token can be kept and handed to a decoder for large integers.

Can a key containing a comma become an exact Go JSON tag?

The Go tag uses commas as option separators. The converter emits a named map of json.RawMessage for an object with an unrepresentable key so the original keys and values survive.

Sources

Put it into practice.

Related guides