Encoding Tables to JSON
Serialize Lua data.
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}All lessons in this course
- Why JSON
- Decoding JSON to Tables
- Encoding Tables to JSON
- Handling Nested Data