feat(plugins): add JSON parsing/serialization (#6420)

Reviewed-by: Mm2PL <mm2pl+gh@kotmisia.pl>
Reviewed-by: pajlada <rasmus.karlsson@pajlada.com>
This commit is contained in:
nerix
2025-11-21 17:43:28 +01:00
committed by GitHub
parent 115428d7f4
commit b63739e792
17 changed files with 1509 additions and 4 deletions
+77
View File
@@ -770,3 +770,80 @@ require("data.file") -- tried to load Plugins/name/data/file.lua and errors beca
#### `print(Args...)`
The `print` global function is equivalent to calling `c2.log(c2.LogLevel.Debug, Args...)`
### JSON API
Chatterino includes the `chatterino.json` module for parsing and serializing JSON:
```lua
local json = require('chatterino.json')
local parsed = json.parse('{"foo": 1}')
-- { foo = 1 }
local str = json.stringify({ foo = 1 })
-- '{"foo":1}'
```
#### `parse(string[, options])`
Parse a string as JSON. Errors if the input was invalid JSON. Use [`pcall`](https://www.lua.org/pil/8.4.html) when parsing untrusted/user input.
```lua
local json = require('chatterino.json')
local parsed = json.parse('{"foo": 1}')
-- { foo = 1 }
local ok, result = pcall(json.parse, 'invalid input')
-- ok = false, result = "Failed to parse JSON: syntax error..."
local ok, result = pcall(json.parse, '{"foo": 1 /* foo */ }', { allow_comments = true })
-- ok = true, result = { foo = 1 }
```
`options` can be an optional table with the following optional keys:
- `allow_comments` (boolean): Allow C++ style comments (`/* foo */` and `// foo`)
- `allow_trailing_commas` (boolean): Allow trailing comments in objects and arrays (`[1, 2,]`)
#### `stringify(value[, options])`
Stringify a Lua value as JSON. Only tables and scalars (strings/numbers/booleans) are supported.
Empty tables are stringified as objects. To get an empty array, use the following: `{ [0] = json.null }` (will produce `[]`).
Tables with `nil` values like `{ foo = nil }` will be stringified as `{}` (they are identical to the empty table).
To get `null` there, use `json.null`.
```lua
local json = require('chatterino.json')
local str = json.stringify({ foo = 1, bar = nil, baz = json.null })
-- '{"foo":1,"baz":null}'
local str = json.stringify({ foo = 1 }, { pretty = true })
-- {
-- "foo": 1
-- }
```
`options` can be an optional table with the following optional keys:
- `pretty` (boolean): Use newlines and indentation when stringifying
- `indent_char` (string, default: space): Character to use when indenting object/array items
- `indent_size` (number, default: 4): Amount of times `indent_char` is repeated per nesting-level
#### `null`
A sentinel to indicate a `null` value.
This is useful if `nil` would hide the value (such as in tables):
```lua
local json = require('chatterino.json')
local str = json.stringify({ foo = 1, bar = nil, baz = json.null })
-- '{"foo":1,"baz":null}'
local obj = json.parse(str)
assert(obj.baz == json.null)
assert(obj.baz ~= nil)
```