Skip to content

Commit bfe2d69

Browse files
committed
SNOW-1871198: Add support for snowflake.snowpark.functions.from_json
1 parent 677e733 commit bfe2d69

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

src/snowflake/snowpark/functions.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,7 @@
202202
ColumnOrName,
203203
ColumnOrSqlExpr,
204204
LiteralType,
205+
type_string_to_type_object,
205206
)
206207
from snowflake.snowpark._internal.udf_utils import check_decorator_args
207208
from snowflake.snowpark._internal.utils import (
@@ -6479,6 +6480,52 @@ def parse_json(e: ColumnOrName, _emit_ast: bool = True) -> Column:
64796480
return builtin("parse_json", _emit_ast=_emit_ast)(c)
64806481

64816482

6483+
@publicapi
6484+
def from_json(
6485+
e: ColumnOrName, schema: Union[str, DataType], _emit_ast: bool = True
6486+
) -> Column:
6487+
"""Parses a column contains a JSON string value into a column of the type specified by schema.
6488+
Schema can be defined as a DataType object or as a compatible type string.
6489+
6490+
Example::
6491+
6492+
>>> from snowflake.snowpark.types import MapType, StringType
6493+
>>> df = session.create_dataframe([('{"key": "value"}',),], schema=["a"])
6494+
>>> df.select(from_json(df.a, MapType(StringType(), StringType()))).show()
6495+
----------------------
6496+
|"from_json(""A"")" |
6497+
----------------------
6498+
|{ |
6499+
| "key": "value" |
6500+
|} |
6501+
----------------------
6502+
<BLANKLINE>
6503+
6504+
Example::
6505+
6506+
>>> df = session.create_dataframe([('[1, 2, 3]',),], schema=["b"])
6507+
>>> df.select(from_json(df.b, "array<integer>")).show()
6508+
----------------------
6509+
|"from_json(""B"")" |
6510+
----------------------
6511+
|[ |
6512+
| 1, |
6513+
| 2, |
6514+
| 3 |
6515+
|] |
6516+
----------------------
6517+
<BLANKLINE>
6518+
"""
6519+
c = _to_col_if_str(e, "from_json")
6520+
if isinstance(schema, str):
6521+
schema = type_string_to_type_object(schema)
6522+
return (
6523+
parse_json(e, _emit_ast=False)
6524+
.cast(schema, _emit_ast=False)
6525+
.alias(f"from_json({c.get_name()})", _emit_ast=False)
6526+
)
6527+
6528+
64826529
@publicapi
64836530
def parse_xml(e: ColumnOrName, _emit_ast: bool = True) -> Column:
64846531
"""Parse the value of the specified column as a JSON string and returns the

0 commit comments

Comments
 (0)