From 33c04d5391b1b6358ed28f97709c93636a7d82ba Mon Sep 17 00:00:00 2001 From: Ned Western Date: Sun, 14 Apr 2024 01:02:32 +1000 Subject: [PATCH] docs(python): Add docstring examples for reading json (#14481) Co-authored-by: Ned Western --- py-polars/polars/io/json.py | 30 ++++++++++++++++++++++++++++++ py-polars/polars/io/ndjson.py | 18 +++++++++++++++++- 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/py-polars/polars/io/json.py b/py-polars/polars/io/json.py index c89af4df0347..1a7b742a08d4 100644 --- a/py-polars/polars/io/json.py +++ b/py-polars/polars/io/json.py @@ -55,6 +55,36 @@ def read_json( See Also -------- read_ndjson + + Examples + -------- + >>> from io import StringIO + >>> json_str = '[{"foo":1,"bar":6},{"foo":2,"bar":7},{"foo":3,"bar":8}]' + >>> pl.read_json(StringIO(json_str)) + shape: (3, 2) + ┌─────┬─────┐ + │ foo ┆ bar │ + │ --- ┆ --- │ + │ i64 ┆ i64 │ + ╞═════╪═════╡ + │ 1 ┆ 6 │ + │ 2 ┆ 7 │ + │ 3 ┆ 8 │ + └─────┴─────┘ + + With the schema defined. + + >>> pl.read_json(StringIO(json_str), schema={"foo": pl.Int64, "bar": pl.Float64}) + shape: (3, 2) + ┌─────┬─────┐ + │ foo ┆ bar │ + │ --- ┆ --- │ + │ i64 ┆ f64 │ + ╞═════╪═════╡ + │ 1 ┆ 6.0 │ + │ 2 ┆ 7.0 │ + │ 3 ┆ 8.0 │ + └─────┴─────┘ """ if isinstance(source, StringIO): source = BytesIO(source.getvalue().encode()) diff --git a/py-polars/polars/io/ndjson.py b/py-polars/polars/io/ndjson.py index 72d1263e8f9d..1c1c2c66e4cd 100644 --- a/py-polars/polars/io/ndjson.py +++ b/py-polars/polars/io/ndjson.py @@ -28,7 +28,7 @@ def read_ndjson( schema_overrides: SchemaDefinition | None = None, ignore_errors: bool = False, ) -> DataFrame: - """ + r""" Read into a DataFrame from a newline delimited JSON file. Parameters @@ -52,6 +52,22 @@ def read_ndjson( any dtypes inferred from the schema param will be overridden. ignore_errors Return `Null` if parsing fails because of schema mismatches. + + Examples + -------- + >>> from io import StringIO + >>> json_str = '{"foo":1,"bar":6}\n{"foo":2,"bar":7}\n{"foo":3,"bar":8}\n' + >>> pl.read_ndjson(StringIO(json_str)) + shape: (3, 2) + ┌─────┬─────┐ + │ foo ┆ bar │ + │ --- ┆ --- │ + │ i64 ┆ i64 │ + ╞═════╪═════╡ + │ 1 ┆ 6 │ + │ 2 ┆ 7 │ + │ 3 ┆ 8 │ + └─────┴─────┘ """ if isinstance(source, StringIO): source = BytesIO(source.getvalue().encode())