|
16 | 16 | importdataclasses |
17 | 17 | importfunctools |
18 | 18 | importitertools |
| 19 | +importjson |
19 | 20 | fromtypingimportcast, Literal, Optional, Sequence, Tuple, Type, TYPE_CHECKING |
20 | 21 |
|
21 | 22 | importpandasaspd |
@@ -429,7 +430,68 @@ def _(self, op: ops.ScalarOp, input: pl.Expr) -> pl.Expr: |
429 | 430 | @compile_op.register(json_ops.JSONDecode) |
430 | 431 | def_(self, op: ops.ScalarOp, input: pl.Expr) ->pl.Expr: |
431 | 432 | assertisinstance(op, json_ops.JSONDecode) |
432 | | -returninput.str.json_decode(_DTYPE_MAPPING[op.to_type]) |
| 433 | +target_dtype=_bigframes_dtype_to_polars_dtype(op.to_type) |
| 434 | +ifop.safe: |
| 435 | +# Polars does not support safe JSON decoding (returning null on failure). |
| 436 | +# We use map_elements to provide safe JSON decoding. |
| 437 | +defsafe_decode(val): |
| 438 | +ifvalisNone: |
| 439 | +returnNone |
| 440 | +try: |
| 441 | +decoded=json.loads(val) |
| 442 | +exceptException: |
| 443 | +returnNone |
| 444 | + |
| 445 | +ifdecodedisNone: |
| 446 | +returnNone |
| 447 | + |
| 448 | +ifop.to_type==bigframes.dtypes.INT_DTYPE: |
| 449 | +iftype(decoded) isbool: |
| 450 | +returnNone |
| 451 | +ifisinstance(decoded, int): |
| 452 | +returndecoded |
| 453 | +ifisinstance(decoded, float): |
| 454 | +ifdecoded.is_integer(): |
| 455 | +returnint(decoded) |
| 456 | +ifisinstance(decoded, str): |
| 457 | +try: |
| 458 | +returnint(decoded) |
| 459 | +exceptException: |
| 460 | +pass |
| 461 | +returnNone |
| 462 | + |
| 463 | +ifop.to_type==bigframes.dtypes.FLOAT_DTYPE: |
| 464 | +iftype(decoded) isbool: |
| 465 | +returnNone |
| 466 | +ifisinstance(decoded, (int, float)): |
| 467 | +returnfloat(decoded) |
| 468 | +ifisinstance(decoded, str): |
| 469 | +try: |
| 470 | +returnfloat(decoded) |
| 471 | +exceptException: |
| 472 | +pass |
| 473 | +returnNone |
| 474 | + |
| 475 | +ifop.to_type==bigframes.dtypes.BOOL_DTYPE: |
| 476 | +ifisinstance(decoded, bool): |
| 477 | +returndecoded |
| 478 | +ifisinstance(decoded, str): |
| 479 | +ifdecoded.lower() =="true": |
| 480 | +returnTrue |
| 481 | +ifdecoded.lower() =="false": |
| 482 | +returnFalse |
| 483 | +returnNone |
| 484 | + |
| 485 | +ifop.to_type==bigframes.dtypes.STRING_DTYPE: |
| 486 | +ifisinstance(decoded, str): |
| 487 | +returndecoded |
| 488 | +returnNone |
| 489 | + |
| 490 | +returndecoded |
| 491 | + |
| 492 | +returninput.map_elements(safe_decode, return_dtype=target_dtype) |
| 493 | + |
| 494 | +returninput.str.json_decode(target_dtype) |
433 | 495 |
|
434 | 496 | @compile_op.register(arr_ops.ToArrayOp) |
435 | 497 | def_(self, op: ops.ToArrayOp, *inputs: pl.Expr) ->pl.Expr: |
|
0 commit comments