JSON ファイル
Polars は、標準の JSON と改行区切り JSON (NDJSON) の両方を読み書きできます。
読み込み
JSON
JSON ファイルの読み込みは、お馴染みの操作です:
df = pl.read_json("docs/data/path.json")
JsonReader
· Available on feature json
use polars::prelude::*;
let mut file = std::fs::File::open("docs/data/path.json").unwrap();
let df = JsonReader::new(&mut file).finish().unwrap();
改行区切り JSON
改行で区切られた JSON オブジェクトは、標準の JSON よりも高パフォーマンスな方法で Polars に読み込むことができます。
Polars は read_ndjson
関数を使って、NDJSON ファイルを DataFrame
に読み込むことができます:
df = pl.read_ndjson("docs/data/path.json")
JsonLineReader
· Available on feature json
let mut file = std::fs::File::open("docs/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/data/path.json")
JsonWriter
· JsonWriter
· Available on feature json
let mut df = df!(
"foo" => &[1, 2, 3],
"bar" => &[None, Some("bak"), Some("baz")],
)
.unwrap();
let mut file = std::fs::File::create("docs/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 の入力を スキャン することができます。スキャンすることで、ファイルの実際の解析を遅延させ、代わりに LazyFrame
と呼ばれる遅延計算のホルダーを返します。
df = pl.scan_ndjson("docs/data/path.json")
LazyJsonLineReader
· Available on feature json
let lf = LazyJsonLineReader::new("docs/data/path.json")
.finish()
.unwrap();