rustserderust-polarspolars

How to serialize json from a polars df in rust


I want get json from polars dataframe, follow this answer Serialize Polars `dataframe` to `serde_json::Value`

use polars::prelude::*;

fn main() {
    let df = df! {
        "a" => [1,2,3,4,5],
    }
    .unwrap();
    let df_json = serde_json::to_value(&df).unwrap();
    println!("df_json {df_json}");
}

output should be

[{"a":1},{"a":2},{"a":3},{"a":4},{"a":5}]

but get

df_json [255,255,255,255,184,0,0,0,4,0,0,0,242,255,255,255,20,0,0,0,4,0,1,0,0,0,10,0,11,0,8,0,10,0,4,0,242,255,255,255,72,0,0,0,16,0,0,0,0,0,10,0,12,0,0,0,4,0,8,0,1,0,0,0,4,0,0,0,244
,255,255,255,24,0,0,0,12,0,0,0,8,0,12,0,4,0,8,0,3,0,0,0,91,48,93,0,9,0,0,0,95,80,76,95,70,76,65,71,83,0,0,0,1,0,0,0,4,0,0,0,236,255,255,255,56,0,0,0,32,0,0,0,24,0,0,0,1,2,0,0,16,0,18
,0,4,0,16,0,17,0,8,0,0,0,12,0,0,0,0,0,244,255,255,255,32,0,0,0,1,0,0,0,8,0,9,0,4,0,8,0,1,0,0,0,97,0,0,0,0,0,0,0,255,255,255,255,136,0,0,0,4,0,0,0,236,255,255,255,64,0,0,0,0,0,0,0,20,
0,0,0,4,0,3,0,12,0,19,0,16,0,18,0,12,0,4,0,230,255,255,255,5,0,0,0,0,0,0,0,64,0,0,0,20,0,0,0,0,0,0,0,0,0,10,0,20,0,4,0,12,0,16,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
,0,20,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,2,0,0,0,3,0,0,0,4,0,0,0,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,0,0,0,0]

how to get right json format?


Solution

  • If you want to build a json string, You could do this. Make sure to enable the json feature in Cargo.toml file

    use std::io::Cursor;
    
    use polars::prelude::*;
    
    fn main() {
        let mut df = df! {
            "a" => [1,2,3,4,5],
        }
        .unwrap();
        
        // Create a file like object or this can be a 
        // json file path to your filesystem. We are
        // using Cursor at the moment, because we want to build the JSON string in memory. 
        let mut file = Cursor::new(Vec::new());
        JsonWriter::new(&mut file)
            .with_json_format(JsonFormat::Json)
            .finish(&mut df)
            .unwrap();
    
        println!("{}", String::from_utf8(file.into_inner()).unwrap()); // Build the JSON string
    }