polars.read_json#

polars.read_json(
source: str | Path | IOBase | bytes,
*,
schema: SchemaDefinition | None = None,
schema_overrides: SchemaDefinition | None = None,
infer_schema_length: int | None = 100,
) DataFrame[source]#

从JSON文件读取到DataFrame中。

Parameters:
source

文件路径或类文件对象(“类文件对象”指的是具有read()方法的对象,例如内置的open函数文件句柄,或BytesIO实例)。对于类文件对象,读取后流位置可能不会相应更新。

schemaSequence of str, (str,DataType) pairs, or a {str:DataType,} dict

DataFrame的模式可以通过几种方式声明:

  • 作为一个{名称:类型}对的字典;如果类型为None,它将自动推断。

  • 作为列名的列表;在这种情况下,类型会自动推断。

  • 作为(名称,类型)对的列表;这等同于字典形式。

如果您提供的列名列表与基础数据中的名称不匹配,此处提供的名称将覆盖它们。模式中提供的名称数量应与基础数据的维度相匹配。

schema_overridesdict, default None

支持类型指定或覆盖一个或多个列;请注意,从schema参数推断出的任何dtypes将被覆盖。

infer_schema_length

用于模式推断的最大扫描行数。 如果设置为None,可能会扫描完整的数据(这很慢)

另请参阅

read_ndjson

示例

>>> 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   │
└─────┴─────┘

定义了模式。

>>> 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 │
└─────┴─────┘