How to convert JSON string into Lua table?


When working with JSON we generally need to decode JSON into a string or maybe encode a string into JSON. Both of these processes of converting the string into a JSON or the opposite are seen frequently.

While Lua doesn’t provide an official library to do the same, we can still make use of the third party libraries.

There are many third party libraries that we can make use of, out of these the most common one is the json-lua library which can be located on this link.

We can either clone the repository on our local machine and then install it or we can simply install it with the help of the luarocks

Enter the following command in your terminal −

luarocks install json-lua

Now, json-lua installed on the local machine, we can make use of the functions it provides.

Example

Consider the example shown below, where we will convert a JSON string into a Lua table, and explore different functions it provides to do so.

JSON = require("JSON")
local t = {
   ["name1"] = "value100",
   ["name2"] = { 1, false, true, 23.54, "a \021 string" }, name3 = JSON:null
}
local encode = JSON:encode (t)
print (encode)
local decode = json:decode( encode )

Output

{"name1":"value100","name3":null,"name2":[1,false,true,23.54,"a \u0015 string"]}

Updated on: 20-Jul-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements