Skip to content

daft.functions.json_array_length#

json_array_length #

json_array_length(expr: Expression) -> Expression

Returns the number of elements in the outermost JSON array.

Returns NULL when the input is NULL, cannot be parsed as JSON, or the parsed JSON is not an array. Equivalent to Spark's json_array_length.

Parameters:

Name Type Description Default
expr Expression

A string expression containing JSON.

required

Returns:

Name Type Description
Expression Expression

An Int32 expression with the array length.

Examples:

1
2
3
4
5
>>> import daft
>>> from daft.functions import json_array_length
>>>
>>> df = daft.from_pydict({"col": ["[1, 2, 3]", "[]", '{"a": 1}', None]})
>>> df.with_column("len", json_array_length(df["col"])).collect()
╭───────────┬───────╮
│ col       ┆ len   │
│ ---       ┆ ---   │
│ String    ┆ Int32 │
╞═══════════╪═══════╡
│ [1, 2, 3] ┆ 3     │
├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ []        ┆ 0     │
├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ {"a": 1}  ┆ None  │
├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ None      ┆ None  │
╰───────────┴───────╯
(Showing first 4 of 4 rows)
Source code in daft/functions/str.py
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
def json_array_length(expr: Expression) -> Expression:
    """Returns the number of elements in the outermost JSON array.

    Returns ``NULL`` when the input is ``NULL``, cannot be parsed as JSON,
    or the parsed JSON is not an array. Equivalent to Spark's
    ``json_array_length``.

    Args:
        expr: A string expression containing JSON.

    Returns:
        Expression: An ``Int32`` expression with the array length.

    Examples:
        >>> import daft
        >>> from daft.functions import json_array_length
        >>>
        >>> df = daft.from_pydict({"col": ["[1, 2, 3]", "[]", '{"a": 1}', None]})
        >>> df.with_column("len", json_array_length(df["col"])).collect()
        ╭───────────┬───────╮
        │ col       ┆ len   │
        │ ---       ┆ ---   │
        │ String    ┆ Int32 │
        ╞═══════════╪═══════╡
        │ [1, 2, 3] ┆ 3     │
        ├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
        │ []        ┆ 0     │
        ├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
        │ {"a": 1}  ┆ None  │
        ├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
        │ None      ┆ None  │
        ╰───────────┴───────╯
        <BLANKLINE>
        (Showing first 4 of 4 rows)
    """
    return Expression._call_builtin_scalar_fn("json_array_length", expr)