How to Encode and Decode JSON and Lua Programming?

LuaServer Side ProgrammingProgramming

JSON is short for JavaScript Object Notation. It is a type of format that is very widely used in the programming world, but it is only a text format in its entirety. There are many JSON libraries available for Lua, but the most commonly used library is lunajson.

In this article, we will learn how to install lunajson first with the help of luarocks and then we will see how to work with luna-json and use it to cover the most common cases of encoding and decoding a string to JSON or vice versa. Finally, we’ll go over some more applicable use cases for JSON.

Installing Lunajson

In order to install Lunajson, we need to install luarocks first, and then with one simple line we can install lunajson, to install luarocks, we need to follow the commands shown below −

sudo apt install luarocks

On a Mac device, we can write the below commands to install Luarocks.

brew update
brew install luarocks

For Windows, we need to follow the guide present at this link.

Now, we just need to install Lunajson. For that, just type the following command in your terminal −

sudo luarocks install lunajson

The above command works on both Mac and Linux, and for windows we need to type the following command −

luarocks install lunajson

Decoding JSON

Now that we know how to set up lunajson on our local machines, it's time to make use of the library to decode JSON.

Consider the example shown below −

Example

#!/usr/bin/lua5.1
lunajson = require 'lunajson'
local jsonraw = '{"test":[1,2,3]}'
local jsonparse = lunajson.decode( jsonraw )
print( jsonparse["test"][ 1 ] .. ", " .. jsonparse["test"][ 2 ] .. ", " .. jsonparse["test"][ 3 ] .. ")

Output

./json1.lua
1, 2, 3

Encoding JSON

Consider the example shown below that depicts the use case of encoding the JSON.

Example

#!/usr/bin/lua5.1
luna = require 'lunajson'
local test = { ["cat"] = { ["name"] = "MeowPow", ["age"] = 5 }, ["dog"] = { ["name"] = "Good Boyyyy", ["age"] = 12 } }
local json = luna.encode( test )
print( json )

Output

./json3.lua
{"cat":{"name":"MeowPow","age":5},"dog":{"name":"Good Boyyyy","age":12}}
raja
Published on 19-Jul-2021 12:26:09
Advertisements