0Pricing
Lua Academy · Lesson

Decoding JSON to Tables

Parse JSON strings.

Decoding JSON to Tables is a free Lua Academy lesson on CoddyKit — lesson 2 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.

Decoding Basics

Decoding turns a JSON string into a Lua value you can work with. The entry point is json.decode(text).

If the top-level JSON is an object you get a Lua table with string keys; if it is an array you get a table with numeric indices.

local json = require("dkjson")
local data = json.decode('{"id": 7}')
print(data.id)

Reading Object Fields

A decoded JSON object behaves like any Lua table. Access values with dot or bracket notation.

Keys that are not valid Lua identifiers (like those with spaces) need bracket syntax.

local json = require("dkjson")
local u = json.decode('{"name": "Mia", "full name": "Mia Lee"}')
print(u.name)
print(u["full name"])

Decoding Arrays

A JSON array decodes into a Lua sequence table indexed from 1. You iterate it with ipairs or a numeric loop.

Remember: Lua arrays start at index 1, not 0.

local json = require("dkjson")
local nums = json.decode('[10, 20, 30]')
for i, v in ipairs(nums) do
  print(i, v)
end

Numbers and Booleans

JSON numbers decode to Lua numbers, and JSON true/false decode to Lua booleans.

You can use them directly in arithmetic or conditionals after decoding.

local json = require("dkjson")
local d = json.decode('{"qty": 3, "paid": false}')
if not d.paid then
  print("unpaid, qty =", d.qty)
end

Handling null

JSON null is tricky because Lua nil removes a key from a table. Libraries handle this differently.

dkjson decodes null to a sentinel value json.null, so the key still exists. Compare against it to detect nulls.

local json = require("dkjson")
local d = json.decode('{"mid": null}')
if d.mid == json.null then
  print("mid is null")
end

Decoding from a File

Often the JSON lives in a file. Read the whole file into a string, then decode it.

This pattern is common for loading config or saved game state.

local json = require("dkjson")
local f = io.open("config.json", "r")
local text = f:read("*a")
f:close()
local cfg = json.decode(text)
print(cfg.theme)

The Three Return Values

dkjson's decode returns up to three values: the decoded result, the position where parsing stopped, and an error message.

On success the result is non-nil; on failure it is nil and the third value explains why.

local json = require("dkjson")
local obj, pos, err = json.decode('{"a":1}')
print(obj.a, pos, err)

Validating Input

Never trust external JSON. Always check the result before using it so a malformed payload does not crash your program.

local json = require("dkjson")
local function safeDecode(s)
  local v, _, err = json.decode(s)
  if not v then return nil, err end
  return v
end

cjson Differences

lua-cjson works similarly but raises an error on invalid input instead of returning it. Wrap it in pcall for safety.

cjson is faster, which matters for high-volume parsing.

local cjson = require("cjson")
local ok, data = pcall(cjson.decode, '{"x":1}')
if ok then print(data.x) else print("error") end

Missing Keys Are nil

If you read a key that was not present in the JSON, Lua simply returns nil. This is normal and does not raise an error.

Use a fallback with or to supply defaults for optional fields.

local json = require("dkjson")
local d = json.decode('{"name": "Sam"}')
local age = d.age or 0
print(d.name, age)

Empty Tables Are Ambiguous

Both an empty JSON object {} and an empty array [] decode to an empty Lua table. After decoding you cannot tell which it was.

This matters mostly when you re-encode; keep that ambiguity in mind for round trips.

Quick Check

Check what you learned about decoding JSON.

Recap

Decoding converts JSON text into Lua tables, with objects becoming string-keyed tables and arrays becoming 1-indexed sequences.

Always validate the result, handle null via the library's sentinel, and remember missing keys are simply nil. Next you will encode Lua tables back into JSON.

Frequently asked questions

Is the “Decoding JSON to Tables” lesson free?

Yes — the full text of “Decoding JSON to Tables” 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 “Decoding JSON to Tables”?

Parse JSON strings. 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 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Decoding JSON to Tables” 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