Added polars struct-encode-json, providing the ability to encode structs as json (#15678)

# Description
This PR introduces `polars struct-encode-json`. This exposes the ability
to encode struct columns as json strings. This is useful when converting
things to formats like CSV that do not support complex types.

```nushell
> ❯ : [[id person]; [1 {name: "Bob", age: 36}] [2 {name: "Betty", age: 63}]]
                    | polars into-df -s {id: i64, person: {name: str, age: u8}}
                    | polars select id (polars col person | polars struct-json-encode | polars as encoded) 
                    | polars collect
╭───┬────┬───────────────────────────╮
│ # │ id │          encoded          │
├───┼────┼───────────────────────────┤
│ 0 │  1 │ {"age":36,"name":"Bob"}   │
│ 1 │  2 │ {"age":63,"name":"Betty"} │
╰───┴────┴───────────────────────────╯
```

# User-Facing Changes
* Added `polars struct-encode-json`, providing the ability to encode
structs as json
This commit is contained in:
Jack Wright
2025-05-06 13:58:51 -07:00
committed by GitHub
parent ce308ee461
commit ff8831318d
3 changed files with 109 additions and 2 deletions

View File

@ -242,8 +242,46 @@ impl PluginTest {
// Check for equality with the result
if !self.value_eq(expectation, &value)? {
// If they're not equal, print a diff of the debug format
let expectation_formatted = format!("{:#?}", expectation);
let value_formatted = format!("{:#?}", value);
let (expectation_formatted, value_formatted) =
match (expectation, &value) {
(
Value::Custom { val: ex_val, .. },
Value::Custom { val: v_val, .. },
) => {
// We have to serialize both custom values before handing them to the plugin
let expectation_serialized =
PluginCustomValue::serialize_from_custom_value(
ex_val.as_ref(),
expectation.span(),
)?
.with_source(self.source.clone());
let value_serialized =
PluginCustomValue::serialize_from_custom_value(
v_val.as_ref(),
expectation.span(),
)?
.with_source(self.source.clone());
let persistent =
self.source.persistent(None)?.get_plugin(None)?;
let expectation_base = persistent
.custom_value_to_base_value(
expectation_serialized
.into_spanned(expectation.span()),
)?;
let value_base = persistent.custom_value_to_base_value(
value_serialized.into_spanned(value.span()),
)?;
(
format!("{:#?}", expectation_base),
format!("{:#?}", value_base),
)
}
_ => (format!("{:#?}", expectation), format!("{:#?}", value)),
};
let diff = diff_by_line(&expectation_formatted, &value_formatted);
failed_header();
eprintln!("{} {}", bold.paint("Result:"), diff);