Xmake provides a built-in json module, based on the implementation of lua_cjson, we can use it to quickly and directly interoperate between json and lua table.
We can use import("core.base.json") for direct import and use.
There are also some examples here: Json Examples
::: tip API
json.decode(jsonstr: <string>)
:::
| Parameter | Description |
|---|---|
| jsonstr | Required. JSON string to decode |
Decodes a JSON string into a Lua table.
import("core.base.json")
local luatable = json.decode('[1,"2", {"a":1, "b":true}]')
print(luatable)
{
1.0,
"2",
{
b = true,
a = 1.0
}
}
::: tip NOTE
If there is null in it, you can use json.null to judge
:::
::: tip API
json.encode(t: <table>)
:::
| Parameter | Description |
|---|---|
| t | Required. Lua table to encode |
Encodes a Lua table into a JSON string.
local jsonstr = json.encode({1, "2", {a = 1}})
It should be noted that if you need to encode null, you need to use json.null, for example
local jsonstr = json.encode({json.null, 1, "2", false, true})
::: tip API
json.loadfile(filepath: <string>)
:::
| Parameter | Description |
|---|---|
| filepath | Required. Path to the JSON file to load |
Loads a JSON file and parses it into a Lua table.
local luatable = json.loadfile("/tmp/xxx.json")
::: tip API
json.savefile(filepath: <string>, data: <table>)
:::
| Parameter | Description |
|---|---|
| filepath | Required. Path to save the JSON file |
| data | Required. Lua table to save |
Saves a Lua table to a JSON file.
json.savefile("/tmp/xxx.json", {1, {a = 1}})