read_json#

ray.data.read_json(paths: str | List[str], *, lines: bool = False, filesystem: pyarrow.fs.FileSystem | None = None, parallelism: int = -1, num_cpus: float | None = None, num_gpus: float | None = None, memory: float | None = None, arrow_open_stream_args: Dict[str, Any] | None = None, partition_filter: PathPartitionFilter | None = None, partitioning: Partitioning = Partitioning(style='hive', base_dir='', field_names=None, field_types={}, filesystem=None, null_fallback=None), include_paths: bool = False, ignore_missing_paths: bool = False, shuffle: Literal['files'] | FileShuffleConfig | None = None, file_extensions: List[str] | None = ['json', 'jsonl', 'json.gz', 'jsonl.gz', 'json.br', 'jsonl.br', 'json.zst', 'jsonl.zst', 'json.lz4', 'jsonl.lz4'], concurrency: int | None = None, override_num_blocks: int | None = None, label_selector: Dict[str, str] | None = None, fallback_strategy: List[Dict[str, Any]] | None = None, max_calls: int | None = None, resources: Dict[str, float] | None = None, accelerator_type: str | None = None, runtime_env: Dict[str, Any] | None = None, ray_remote_args: Dict[str, Any] = None, **arrow_json_args) → Dataset[source]#

Creates a Dataset from JSON and JSONL files.

For JSON file, the whole file is read as one row. For JSONL file, each line of file is read as separate row.

Note

The DataSourceV2 reader is selected through the use_datasource_v2 setting of DataContext. It splits each large uncompressed JSON Lines file into byte ranges read by separate tasks: every such file when lines=True, else only .jsonl files.

With lines=False it parses with pyarrow.json, inferring column types per piece, so a column of whole numbers early in a file and decimals later is int64 in some blocks and double in others. Pass parse_options=pyarrow.json.ParseOptions(explicit_schema=...) to pin the types. A .jsonl file larger than the chunk size is parsed only as JSON Lines: unlike a whole file, a chunk can’t fall back to json.load, so a .jsonl file holding one array raises.

With lines=True it parses with pandas.read_json, as V1 does, and produces pandas blocks, so the schema is known only once a block is read. Each pandas block infers its own types. Strings become timestamps only in columns named like dates, numeric strings become numbers, and integer columns with nulls become floats. Nested objects stay Python objects, and a line that is an array becomes a row with columns "0", "1", and so on.

arrow_open_stream_args, and JSON options other than read_options and parse_options, use the V1 reader. To use the V1 reader everywhere, set ray.data.DataContext.get_current().use_datasource_v2 = False, or RAY_DATA_USE_DATASOURCE_V2=0 in the environment before importing Ray.

Examples

Read a JSON file in remote storage.

>>> import ray
>>> ds = ray.data.read_json("s3://anonymous@ray-example-data/log.json")
>>> ds.schema()
Column     Type
------     ----
timestamp  timestamp[...]
size       int64

Read a JSONL file in remote storage.

>>> ds = ray.data.read_json("s3://anonymous@ray-example-data/train.jsonl", lines=True)
>>> ds.schema()
Column  Type
------  ----
input   <class 'object'>

Read multiple local files.

>>> ray.data.read_json(
...    ["local:///path/to/file1", "local:///path/to/file2"])

Read multiple directories.

>>> ray.data.read_json(
...     ["s3://bucket/path1", "s3://bucket/path2"])

By default, read_json() parses Hive-style partitions from file paths. If your data adheres to a different partitioning scheme, set the partitioning parameter.

>>> ds = ray.data.read_json("s3://anonymous@ray-example-data/year=2022/month=09/sales.json")
>>> ds.take(1)
[{'order_number': 10107, 'quantity': 30, 'year': '2022', 'month': '09'}]
Parameters:
  • paths (str | List[str]) – A single file or directory, or a list of file or directory paths. A list of paths can contain both files and directories.

  • lines (bool) – [Experimental] If True, read files assuming line-delimited JSON. This mode doesn’t support the filesystem, arrow_open_stream_args, or arrow_json_args parameters.

  • filesystem (pyarrow.fs.FileSystem | None) – The PyArrow filesystem implementation to read from. These filesystems are specified in the PyArrow docs. Specify this parameter if you need to provide specific configurations to the filesystem. By default, the filesystem is automatically selected based on the scheme of the paths. For example, if the path begins with s3://, the S3FileSystem is used.

  • parallelism (int) – This argument is deprecated. Use override_num_blocks argument.

  • num_cpus (float | None) – The number of CPUs to reserve for each parallel read worker.

  • num_gpus (float | None) – The number of GPUs to reserve for each parallel read worker. For example, specify num_gpus=1 to request 1 GPU for each parallel read worker.

  • memory (float | None) – The heap memory in bytes to reserve for each parallel read worker.

  • arrow_open_stream_args (Dict[str, Any] | None) – kwargs passed to pyarrow.fs.FileSystem.open_input_file. when opening input files to read.

  • partition_filter (PathPartitionFilter | None) – A PathPartitionFilter. Use with a custom callback to read only selected partitions of a dataset. By default, this filters out any file paths whose file extension does not match “.json” or “.jsonl”.

  • partitioning (Partitioning) –

    A Partitioning object that describes how paths are organized. By default, this function parses Hive-style partitions. The partition values from a file’s path become columns. If the file also has a column with the same name, the path value must equal the file’s values, or reading raises a ValueError: country=US/a.jsonl with rows containing country=CA fails.

  • include_paths (bool) – If True, include the path to each file. File paths are stored in the 'path' column.

  • ignore_missing_paths (bool) – If True, ignores any file paths in paths that are not found. Defaults to False.

  • shuffle (Literal['files'] | ~ray.data.datasource.file_based_datasource.FileShuffleConfig | None) – If setting to “files”, randomly shuffle input files order before read. If setting to FileShuffleConfig, you can pass a random seed to shuffle the input files, e.g. FileShuffleConfig(seed=42). Defaults to not shuffle with None.

  • file_extensions (List[str] | None) – A list of file extensions to filter files by.

  • concurrency (int | None) – The maximum number of Ray tasks to run concurrently. Set this to control number of tasks to run concurrently. This doesn’t change the total number of tasks run or the total number of output blocks. By default, concurrency is dynamically decided based on the available resources.

  • override_num_blocks (int | None) – Override the number of output blocks from all read tasks. By default, the number of output blocks is dynamically decided based on input data size and available resources. You shouldn’t manually set this value in most cases.

  • label_selector (Dict[str, str] | None) – Labels required on the node where each read task runs.

  • fallback_strategy (List[Dict[str, Any]] | None) – Alternative label requirements that Ray tries in order if label_selector can’t be satisfied.

  • max_calls (int | None) – The maximum number of read tasks a worker runs before exiting.

  • resources (Dict[str, float] | None) – Custom resources to reserve for each read task, expressed as a mapping from resource name to quantity.

  • accelerator_type (str | None) – The accelerator type required for each read task.

  • runtime_env (Dict[str, Any] | None) – The runtime environment to use for each read task.

  • ray_remote_args (Dict[str, Any]) – Additional options passed to ray.remote() for each read task. This argument is deprecated and will be removed in Ray 2.64. Use the named remote parameters instead.

  • **arrow_json_args – JSON read options to pass to pyarrow.json.read_json.

Returns:

Dataset producing records read from the specified paths.

Return type:

Dataset