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

# json.encode

> 使用 Real JSON encoder 将 Lua value serialize 为 JSON string。json.stringify 注册到同一个 function。

<div className="real-function-page">
  ```lua theme={null}
  json.encode(value: any, options?: EncodeOptions): string
  ```

  ## 参数

  <ParamField path={"value"} type={"any"} required>
    要 encode 的 Value。nil、booleans、numbers、strings、tables 和 json.null 会直接处理。Unsupported Lua types 默认 encode 为 null，除非 errorOnUnsupported 为 true。
  </ParamField>

  <ParamField path={"options"} type={"EncodeOptions"}>
    Optional encode options。boolean 切换 pretty output。number 会用 clamp 到 0.16 的 spaces 数量启用 pretty output。string 会用该 indent 启用 pretty output。table 可以设置 pretty、sortKeys、emptyTableAsArray、errorOnUnsupported、encodeInvalidNumbersAsNull、maxDepth 和 indent。
  </ParamField>

  ## 返回值

  <ResponseField name={"json"} type={"string"}>
    Encoded JSON string。Encoding errors 会作为 Luau errors 抛出。
  </ResponseField>

  ## 类型

  ### EncodeOptions

  控制 JSON 序列化和格式设置。

  | Name                         | Type      | Required | 说明                       |
  | ---------------------------- | --------- | -------- | ------------------------ |
  | `pretty`                     | `boolean` | No       | 启用格式化的多行 JSON 输出。        |
  | `sortKeys`                   | `boolean` | No       | 在编码之前对对象键进行排序。           |
  | `emptyTableAsArray`          | `boolean` | No       | 将空表编码为数组而不是对象。           |
  | `errorOnUnsupported`         | `boolean` | No       | 引发错误而不是替换不受支持的值。         |
  | `encodeInvalidNumbersAsNull` | `boolean` | No       | 将 NaN 和无限数编码为 JSON null。 |
  | `maxDepth`                   | `integer` | No       | 设置最大嵌套深度，范围为 1 到 4096。   |
  | `indent`                     | `string`  | No       | 设置缩进字符串，限制为 32 个字符。      |

  ## 示例

  Encode JSON-compatible values；当 empty array 必须保持为 array 时使用 json.array。

  ```lua theme={null}
  local payload = {
      name = "Real",
      enabled = true,
      tags = json.array({ "api", "docs" }),
      missing = json.null,
  }

  local text = json.encode(payload, {
      sortKeys = true,
  })

  print(text)
  ```
</div>
