Json in Lua

Our first example will demonstrate encoding and decoding of JSON data in Lua. We’ll use the json module, which is not part of the Lua standard library but can be installed separately.

local json = require("json")

-- We'll use these two tables to demonstrate encoding and
-- decoding of custom types below.
local response1 = {
    page = 1,
    fruits = {"apple", "peach", "pear"}
}

local response2 = {
    page = 1,
    fruits = {"apple", "peach", "pear"}
}

-- First we'll look at encoding basic data types to
-- JSON strings. Here are some examples for atomic values.
print(json.encode(true))
print(json.encode(1))
print(json.encode(2.34))
print(json.encode("gopher"))

-- And here are some for tables, which encode
-- to JSON arrays and objects as you'd expect.
local slcD = {"apple", "peach", "pear"}
print(json.encode(slcD))

local mapD = {apple = 5, lettuce = 7}
print(json.encode(mapD))

-- The JSON module can automatically encode your
-- custom data types.
print(json.encode(response1))
print(json.encode(response2))

-- Now let's look at decoding JSON data into Lua
-- values. Here's an example for a generic data structure.
local byt = '{"num":6.13,"strs":["a","b"]}'

-- We need to provide a variable where the JSON
-- module can put the decoded data. This will be a table.
local dat = json.decode(byt)
print(json.encode(dat))  -- Re-encode to print

-- In order to use the values in the decoded table,
-- we can access them directly.
local num = dat.num
print(num)

-- Accessing nested data is straightforward in Lua.
local str1 = dat.strs[1]
print(str1)

-- We can also decode JSON into custom data types.
local str = '{"page": 1, "fruits": ["apple", "peach"]}'
local res = json.decode(str)
print(json.encode(res))
print(res.fruits[1])

-- In Lua, we can write JSON directly to a file or
-- any other output stream.
local file = io.open("output.json", "w")
file:write(json.encode({apple = 5, lettuce = 7}))
file:close()

To run this program, save it as json_example.lua and use the Lua interpreter:

$ lua json_example.lua
true
1
2.34
"gopher"
["apple","peach","pear"]
{"apple":5,"lettuce":7}
{"page":1,"fruits":["apple","peach","pear"]}
{"page":1,"fruits":["apple","peach","pear"]}
{"num":6.13,"strs":["a","b"]}
6.13
a
{"page":1,"fruits":["apple","peach"]}
apple

We’ve covered the basics of JSON in Lua here. Note that the exact output format might vary slightly depending on the specific JSON module you’re using. Also, unlike Go, Lua doesn’t have static typing, so we don’t need to worry about type assertions when accessing decoded data.

Remember to install a JSON module for Lua before running this code. You can typically do this using a package manager like LuaRocks:

$ luarocks install luajson

This example uses the luajson module, but there are other JSON modules available for Lua as well.