Method: Polars::StringExpr#json_decode

Defined in:
lib/polars/string_expr.rb

#json_decode(dtype, infer_schema_length: nil) ⇒ Expr

Parse string values as JSON.

Throw errors if encounter invalid JSON strings.

Examples:

df = Polars::DataFrame.new(
  {"json" => ['{"a":1, "b": true}', nil, '{"a":2, "b": false}']}
)
dtype = Polars::Struct.new([Polars::Field.new("a", Polars::Int64), Polars::Field.new("b", Polars::Boolean)])
df.with_columns(decoded: Polars.col("json").str.json_decode(dtype))
# =>
# shape: (3, 2)
# ┌─────────────────────┬───────────┐
# │ json                ┆ decoded   │
# │ ---                 ┆ ---       │
# │ str                 ┆ struct[2] │
# ╞═════════════════════╪═══════════╡
# │ {"a":1, "b": true}  ┆ {1,true}  │
# │ null                ┆ null      │
# │ {"a":2, "b": false} ┆ {2,false} │
# └─────────────────────┴───────────┘

Parameters:

  • dtype (Object)

    The dtype to cast the extracted value to.

  • infer_schema_length (Integer) (defaults to: nil)

    Deprecated and ignored.

Returns:



960
961
962
963
964
965
966
967
968
# File 'lib/polars/string_expr.rb', line 960

def json_decode(dtype, infer_schema_length: nil)
  if dtype.nil?
    msg = "`Expr.str.json_decode` needs an explicitly given `dtype` otherwise Polars is not able to determine the output type. If you want to eagerly infer datatype you can use `Series.str.json_decode`."
    raise TypeError, msg
  end

  dtype_expr = Utils.parse_into_datatype_expr(dtype)._rbdatatype_expr
  Utils.wrap_expr(_rbexpr.str_json_decode(dtype_expr))
end