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

# json_length

> 返回 JSON 文档的长度。

返回 JSON 文档的长度。如果指定了路径，该函数返回路径所标识的值的长度。

**Tip**

所有的 JSON 函数和操作符都列在导航栏和[概览页面](/documents/cn/4.2/sql-reference/sql-functions/json-functions/overview-of-json-functions-and-operators.md)上

通过[生成列](/documents/cn/4.2/sql-reference/sql-statements/generated_columns.md)加速查询

文档的长度根据以下规则确定：

* 标量值的长度为 1。例如，`1`、`"a"`、`true`、`false` 和 `null` 的长度为 1。

* 数组的长度是数组元素的数量。例如，`[1, 2]` 的长度为 2。

* 对象的长度是对象成员的数量。例如，`{"a": 1}` 的长度为 1。

* 嵌套数组或对象的长度不计算在内。例如，`{"a": [1, 2]}` 的长度为 1，因为嵌套数组 `[1, 2]` 不计入长度。

## 语法

```Haskell theme={null}
json_length(json_doc[, path])
```

## 参数

`json_doc`：必需，返回其长度的 JSON 文档。

`path`：可选。用于返回文档中某个值的长度。路径通常以 `$` 开始，并使用 `.` 作为路径分隔符。`[]` 用作数组下标，从 0 开始。

## 返回值

返回 INT 类型的值。

如果 JSON 文档不是有效文档，则返回错误。

在以下任一情况下返回 0：

* **`path`** 未标识文档中的值。

* 路径不是有效的路径表达式。

* 路径包含 `*` 或 `**` 通配符。

## 示例

示例 1：返回标量值的长度。

```Plain theme={null}
select json_length('1');
+------------------+
| json_length('1') |
+------------------+
|                1 |
+------------------+
```

示例 2：返回空对象的长度。

```Plain theme={null}
select json_length('{}');
+-------------------+
| json_length('{}') |
+-------------------+
|                 0 |
+-------------------+
```

示例 3：返回有数据的对象的长度。

```Plain theme={null}
select json_length('{"Name": "Homer"}');
+----------------------------------+
| json_length('{"Name": "Homer"}') |
+----------------------------------+
|                                1 |
+----------------------------------+
```

示例 4：返回 JSON 数组的长度。

```plain text theme={null}
select json_length('[1, 2, 3]');
+--------------------------+
| json_length('[1, 2, 3]') |
+--------------------------+
|                        3 |
+--------------------------+
```

示例 5：返回包含嵌套数组的 JSON 数组的长度。

嵌套数组 `[3, 4]` 不计入长度。

```plain text theme={null}
select json_length('[1, 2, [3, 4]]');
+-------------------------------+
| json_length('[1, 2, [3, 4]]') |
+-------------------------------+
|                             3 |
+-------------------------------+
```

示例 6：返回由路径 `$.Person` 指定的对象的长度。

```SQL theme={null}
SET @file = '{  
    "Person": {    
       "Name": "Homer", 
       "Age": 39,
       "Hobbies": ["Eating", "Sleeping"]  
    }
 }';
select json_length(@file, '$.Person') 'Result';
```

示例 7：返回由路径 `$.y` 指定的值的长度。

```plain text theme={null}
select json_length('{"x": 1, "y": [1, 2]}', '$.y');
+---------------------------------------------+
| json_length('{"x": 1, "y": [1, 2]}', '$.y') |
+---------------------------------------------+
|                                           2 |
+---------------------------------------------+
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.