Reading and writing JSON (uses cJSON)
More...
JSON objects become Lua tables with string keys, JSON arrays become Lua lists (starting at index 1), and the other way around.
local data = json.decode('{"name": "LifeLua", "tags": ["lua", "vita"], "stars": 5}')
print(data.name, data.tags[1], data.stars) -- LifeLua lua 5
data.stars = data.stars + 1
local text = json.encode(data)
JSON's null can't be stored as Lua's nil (a table can't hold nil), so it's represented by a special value instead. Use json.isnull() to check for it, and json.null to write it.
|
|
jsonnull | json.null |
| | The value used for JSON null. Put it in a table to write null, e.g. json.encode({score = json.null}) gives {"score": null}
|
| |
◆ json.decode()
| table json.decode |
( |
string | json | ) |
|
Converts a JSON string to a Lua value
json.parse() is the same function under another name.
- Parameters
-
- Returns
- The resulting table (or string/number/boolean, if the JSON is just one value). Raises an error if the JSON is invalid.
◆ json.encode()
| string json.encode |
( |
table | value, |
|
|
boolean | minified ) |
Converts a Lua value to a JSON string. A table whose keys are all numbers becomes a JSON array, any other table becomes a JSON object (keys that aren't strings are skipped). Functions and other unsupported values become null.
json.stringify() is the same function under another name.
- Parameters
-
| value | The table (or other value) to convert |
| minified | true to leave out the spaces and line breaks (optional, default: false, the JSON is nicely formatted) |
- Returns
- The JSON text
◆ json.isnull()
| boolean json.isnull |
( |
any | value | ) |
|
Checks if a value is JSON's null
- Parameters
-
- Returns
true if the value is JSON null
- Example:
local data = json.decode('{"score": null}')
if json.isnull(data.score) then print("No score yet") end
◆ json.minify()
| string json.minify |
( |
string | json | ) |
|
Removes all spaces, line breaks and comments from a JSON string
- Parameters
-
- Returns
- The minified JSON text
◆ json.parse()
| table json.parse |
( |
string | json | ) |
|
◆ json.stringify()
| string json.stringify |
( |
table | value, |
|
|
boolean | minified ) |
Same as json.encode()
- Parameters
-
| value | The table (or other value) to convert |
| minified | true to leave out the spaces and line breaks (optional, default: false) |
- Returns
- The JSON text
◆ json.version()
Gets the version of the cJSON library
- Returns
- The version, e.g.
"1.7.19"