Skip to content

Commit

Permalink
docs(python): Add docstring examples for reading json (#14481)
Browse files Browse the repository at this point in the history
Co-authored-by: Ned Western <[email protected]>
  • Loading branch information
NedJWestern and Ned Western authored Apr 13, 2024
1 parent 429d3dd commit 33c04d5
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
30 changes: 30 additions & 0 deletions py-polars/polars/io/json.py
Original file line number Diff line number Diff line change
Expand Up @@ -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())
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 @@ -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
Expand All @@ -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())
Expand Down

0 comments on commit 33c04d5

Please sign in to comment.