Lua by Example: JSON and Library Loading

Lua does not have built in JSON support. However there are many open source libraries available from the community. The Lua Wiki has a listing of json libraries

The examples here use the jf-JSON library

The require function searches LUA_PATH and LUA_CPATH For more about require see the Section 8.1 of the PIL guide

local JSON = require 'jfjson'
local inspect = require 'inspect'
local lua_value = JSON:decode('[ "Larry", "Curly", "Moe" ]')
print('json array -> lua', inspect(lua_value))
local raw_json_text = JSON:encode({ "a", "b", "c"})
print('lua -> json array: ', raw_json_text)
local raw_json_map = JSON:encode({
    ['key'] = 'value'
})
print('lua -> json map: ', raw_json_map)

We can override the LUA_PATH variable and ask all require calls to search the locations listed in order from left to right. If LUA_PATH is unset the default is typically ?;?.lua

$ LUA_PATH="?;?.lua;lib/?.lua" lua json.lua
json array -> lua    { "Larry", "Curly", "Moe" }
lua -> json array:     ["a","b","c"]
lua -> json map:     {"key":"value"}

Next example: Command-Line Arguments.