> ## 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.tryDecode

> 使用与 json.decodeSafe 相同的 function 尝试 parse JSON string，并为 parse errors 返回 status values。

<div className="real-function-page">
  ```lua theme={null}
  json.tryDecode(json: string, options?: DecodeOptions): boolean | any | nil | string | nil | number | nil
  ```

  ## 参数

  <ParamField path={"json"} type={"string"} required>
    要 parse 的 JSON string。function 使用 string type checking 读取这个 argument。
  </ParamField>

  <ParamField path={"options"} type={"DecodeOptions"}>
    Optional decode options。boolean 设置 useNull。table 可以设置 useNull 和 maxDepth。
  </ParamField>

  ## 返回值

  <ResponseField name={"success"} type={"boolean"}>
    parsing 成功时为 true，在 protected parse block 内 parsing 失败时为 false。
  </ResponseField>

  <ResponseField name={"decoded"} type={"any | nil"}>
    success 时的 decoded value。parse failure 时此 return 为 nil。
  </ResponseField>

  <ResponseField name={"errorMessage"} type={"string | nil"}>
    parse failure 时的 error message。Message 以 json.decodeSafe 为 prefix，并包含 near-position suffix。
  </ResponseField>

  <ResponseField name={"errorPosition"} type={"number | nil"}>
    parse failure 时 parser 的 parser byte position。此 return 只在 failure 时存在。
  </ResponseField>

  ## 类型

  ### DecodeOptions

  控制 JSON 解析行为。

  | Name       | Type      | Required | 说明                                 |
  | ---------- | --------- | -------- | ---------------------------------- |
  | `useNull`  | `boolean` | No       | 使用库的 null 标记而不是 nil 来表示 JSON null。 |
  | `maxDepth` | `integer` | No       | 设置最大嵌套深度，范围为 1 到 4096。             |

  ## 示例

  使用 json.decodeSafe-compatible alias 以 status returns decode JSON。

  ```lua theme={null}
  local ok, value, message, position = json.tryDecode('{"ready":true,"missing":null}', {
      useNull = true,
  })

  if ok then
      print(value.ready)
      print(json.isNull(value.missing))
  else
      warn(message, position)
  end
  ```
</div>
