0Pricing
Lua Academy · Lesson

Decoding JSON to Tables

Parse JSON strings.

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"])

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