lua table to json
-- Step 1: Require the cjson module
local cjson = require("cjson")
-- Step 2: Define a Lua table
local myTable = {
name = "John",
age = 30,
city = "New York",
hobbies = {"reading", "traveling", "coding"},
address = {
street = "123 Main St",
zip = "10001"
}
}
-- Step 3: Convert the Lua table to a JSON-formatted string
local jsonString = cjson.encode(myTable)
-- Step 4: Print the JSON-formatted string
print(jsonString)
In this example, we use the cjson
module, which is a JSON encoding and decoding module for Lua. First, we require the module in Step 1. Then, in Step 2, we define a Lua table (myTable
) with various types of data, including strings, numbers, an array (hobbies
), and a nested table (address
).
In Step 3, we use the cjson.encode()
function to convert the Lua table into a JSON-formatted string (jsonString
). Finally, in Step 4, we print the resulting JSON string to the console.