跳到内容

JSON 文件

Polars 可以读写标准 JSON 和换行符分隔的 JSON (NDJSON)。

读取

JSON

读取 JSON 文件应该很熟悉

read_json

df = pl.read_json("docs/assets/data/path.json")

JsonReader · 在特性 json 上可用

use polars::prelude::*;

let mut file = std::fs::File::open("docs/assets/data/path.json").unwrap();
let df = JsonReader::new(&mut file).finish()?;

换行符分隔的 JSON

通过换行符分隔的 JSON 对象可以比标准 JSON 以更高的性能读入 Polars。

Polars 可以使用 read_ndjson 函数将 NDJSON 文件读入 DataFrame

read_ndjson

df = pl.read_ndjson("docs/assets/data/path.json")

JsonLineReader · 在特性 json 上可用

let mut file = std::fs::File::open("docs/assets/data/path.json").unwrap();
let df = JsonLineReader::new(&mut file).finish().unwrap();

写入

write_json · write_ndjson

df = pl.DataFrame({"foo": [1, 2, 3], "bar": [None, "bak", "baz"]})
df.write_json("docs/assets/data/path.json")

JsonWriter · JsonWriter · 在特性 json 上可用

let mut df = df!(
    "foo" => &[1, 2, 3],
    "bar" => &[None, Some("bak"), Some("baz")],
)
.unwrap();

let mut file = std::fs::File::create("docs/assets/data/path.json").unwrap();

// json
JsonWriter::new(&mut file)
    .with_json_format(JsonFormat::Json)
    .finish(&mut df)
    .unwrap();

// ndjson
JsonWriter::new(&mut file)
    .with_json_format(JsonFormat::JsonLines)
    .finish(&mut df)
    .unwrap();

扫描

Polars 允许您**仅对换行符分隔的 JSON** 扫描 JSON 输入。扫描会延迟文件的实际解析,而是返回一个名为 LazyFrame 的惰性计算持有者。

scan_ndjson

df = pl.scan_ndjson("docs/assets/data/path.json")

LazyJsonLineReader · 在特性 json 上可用

let lf = LazyJsonLineReader::new("docs/assets/data/path.json")
    .finish()
    .unwrap();