Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs(python): Add docstring examples for reading json #14481

Merged
merged 2 commits into from
Apr 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions py-polars/polars/io/json.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,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 │
└─────┴─────┘
"""
return pl.DataFrame._read_json(
source,
Expand Down
18 changes: 17 additions & 1 deletion py-polars/polars/io/ndjson.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,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
Expand All @@ -45,6 +45,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 │
└─────┴─────┘
"""
return pl.DataFrame._read_ndjson(
source,
Expand Down