JSON 文件
Polars 可以读取和写入标准 JSON 和换行分隔的 JSON (NDJSON)。
读取
JSON
读取JSON文件应该看起来很熟悉:
df = pl.read_json("docs/assets/data/path.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 中:
df = pl.read_ndjson("docs/assets/data/path.json")
let mut file = std::fs::File::open("docs/assets/data/path.json").unwrap();
let df = JsonLineReader::new(&mut file).finish().unwrap();
写入
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 的惰性计算持有者。
df = pl.scan_ndjson("docs/assets/data/path.json")
LazyJsonLineReader · 可在功能 json 上使用
let lf = LazyJsonLineReader::new("docs/assets/data/path.json")
.finish()
.unwrap();