> ## Documentation Index
> Fetch the complete documentation index at: https://lua.starline.one/llms.txt
> Use this file to discover all available pages before exploring further.

# JSON

> Encode and decode JSON values in Starline Lua scripts.

```lua theme={"dark"}
local data, err = json.Decode('{"name":"de_dust2","rounds":[1,2,3]}')
print(data.name)        -- de_dust2
print(#data.rounds)     -- 3

local body = json.Encode({ q = "hello", target = "da" })
```

## Decode

```lua theme={"dark"}
local value, err = json.Decode(text)
```

Returns the decoded value, or `nil` plus an error string if the text is not valid JSON.

| JSON         | Lua                    |
| ------------ | ---------------------- |
| object       | Table with string keys |
| array        | Table, 1-based         |
| string       | String                 |
| number       | Number                 |
| true / false | Boolean                |
| null         | `json.null`            |

## Encode

```lua theme={"dark"}
local text, err = json.Encode(value)
```

Returns the JSON text, or `nil` plus an error string. Functions, userdata and threads cannot be encoded.

| Lua                             | JSON                                             |
| ------------------------------- | ------------------------------------------------ |
| Table, keys `1..n` with no gaps | array                                            |
| Table, anything else            | object                                           |
| String                          | string                                           |
| Number                          | number, with non-finite values written as `null` |
| Boolean                         | true / false                                     |
| `nil`, `json.null`              | null                                             |
| `json.EmptyObject`              | `{}`                                             |

Object keys must be strings or numbers. Number keys are converted to strings.

## null

`json.null` preserves JSON `null` values inside Lua tables and encodes back to `null`.

```lua theme={"dark"}
local v = json.Decode('{"a":null}')
if v.a == json.null then print("a was null, not missing") end
```

## Empty tables

`{}` and `[]` both decode to an empty Lua table, and an empty table encodes to `[]`. Use `json.EmptyObject` when a server needs `{}`.

```lua theme={"dark"}
json.Encode({ filters = json.EmptyObject })   -- {"filters":{}}
```

## With HTTP

```lua theme={"dark"}
http.Post(url, json.Encode({ text = "hello", to = "da" }), {
    headers = { ["Content-Type"] = "application/json" },
}, function(res)
    if not res.ok then return end
    local data = json.Decode(res.body)
    if data then print(data.translation) end
end)
```

Nesting is capped at 200 levels deep, which also stops a table that contains itself from encoding forever.
