0Pricing
Lua Academy · Lesson

Encoding Tables to JSON

Serialize Lua data.

Encoding Tables to JSON is a free Lua Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Lua Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Encoding Basics

Encoding is the reverse of decoding: it turns a Lua table into a JSON string. Call json.encode(table).

The result is a single-line string you can write to a file or send over the network.

local json = require("dkjson")
local t = { name = "Leo", age = 9 }
print(json.encode(t))

Objects vs Arrays

How a Lua table encodes depends on its keys. A table with consecutive integer keys from 1 becomes a JSON array.

A table with string keys becomes a JSON object. Mixed tables are ambiguous and should be avoided.

local json = require("dkjson")
print(json.encode({ 1, 2, 3 }))        -- [1,2,3]
print(json.encode({ a = 1, b = 2 }))   -- {"a":1,"b":2}

Pretty Printing

By default JSON is compact. dkjson can indent the output for readability by passing an options table with indent = true.

Pretty output is great for config files humans will edit.

local json = require("dkjson")
local t = { name = "Ann", roles = { "dev", "lead" } }
print(json.encode(t, { indent = true }))

Encoding Numbers and Booleans

Lua numbers and booleans encode directly to their JSON counterparts. Integers and floats both become JSON numbers.

local json = require("dkjson")
local t = { count = 5, ratio = 1.5, active = true }
print(json.encode(t))

The nil Problem

You cannot store nil in a table to mean JSON null because assigning nil removes the key entirely.

To emit a literal null, use the library sentinel json.null as the value.

local json = require("dkjson")
local t = { middle = json.null }
print(json.encode(t))  -- {"middle":null}

Sparse Arrays Break

If a sequence has a gap (for example index 2 is nil), Lua no longer treats it as a clean array. Encoding may stop at the gap or behave oddly.

Keep array indices contiguous starting at 1 for predictable JSON arrays.

local json = require("dkjson")
local t = { [1] = "a", [3] = "c" }  -- gap at 2
print(json.encode(t))               -- unreliable

Writing JSON to a File

To persist data, encode the table to a string and write that string to a file.

This is how you save settings, scores, or any structured state.

local json = require("dkjson")
local data = { theme = "dark", volume = 8 }
local f = io.open("settings.json", "w")
f:write(json.encode(data, { indent = true }))
f:close()

Empty Table Defaults to Object

An empty Lua table {} has no keys, so dkjson encodes it as an empty object {} by default, not an array.

If you need an empty array, dkjson lets you tag the table; otherwise the type is ambiguous.

local json = require("dkjson")
print(json.encode({}))  -- {}

Key Order Is Not Guaranteed

Lua tables have no inherent order for string keys, so the order of fields in the encoded JSON may vary.

Do not rely on field order; JSON consumers should look up keys by name, not position.

Round Trip Consistency

Encoding then decoding should give you an equivalent table. This round trip is a good way to test your data handling.

local json = require("dkjson")
local orig = { a = 1, list = { 2, 3 } }
local copy = json.decode(json.encode(orig))
print(copy.a, copy.list[2])

Encoding with cjson

lua-cjson also offers encode. It is faster but has fewer formatting options and raises errors instead of returning them.

For pretty indented output, dkjson is usually the friendlier choice.

local cjson = require("cjson")
local s = cjson.encode({ ok = true, n = 42 })
print(s)

Quick Check

Test your grasp of encoding Lua tables.

Recap

Encoding turns Lua tables into JSON strings. Integer-keyed sequences become arrays and string-keyed tables become objects.

Use json.null for literal nulls, keep arrays contiguous, and pass indent = true for readable output. Next you will tackle deeply nested data.

Frequently asked questions

Is the “Encoding Tables to JSON” lesson free?

Yes — the full text of “Encoding Tables to JSON” is free to read here on the web, and the Lua Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Lua Academy course, upgrade to CoddyKit PRO.

What will I learn in “Encoding Tables to JSON”?

Serialize Lua data. You practise Lua Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Lua Academy?

No prior experience is required. Lua Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Encoding Tables to JSON” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Lua Academy lesson?

Yes. Every Lua Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Why JSON
  2. Decoding JSON to Tables
  3. Encoding Tables to JSON
  4. Handling Nested Data
← Back to Lua Academy