|
| 1 | +""" |
| 2 | +Adds support for working with newline-delimited JSON (ndjson) files. This format is useful for |
| 3 | +streaming json content that would otherwise not be possible using raw JSON files. |
| 4 | +""" |
| 5 | + |
| 6 | +import json |
| 7 | +from typing import IO, Any |
| 8 | + |
| 9 | + |
| 10 | +def dumps(obj: list[dict[str, Any]], **kwargs) -> str: |
| 11 | + """ |
| 12 | + Converts the list of dictionaries into string representation |
| 13 | +
|
| 14 | + Args: |
| 15 | + obj (list[dict[str, Any]]): List of dictionaries to convert |
| 16 | + **kwargs: Additional keyword arguments to pass to json.dumps |
| 17 | +
|
| 18 | + Returns: |
| 19 | + str: string representation of the list of dictionaries |
| 20 | + """ |
| 21 | + return "\n".join(json.dumps(each, **kwargs) for each in obj) |
| 22 | + |
| 23 | + |
| 24 | +def dump(obj: list[dict[str, Any]], fp: IO, **kwargs) -> None: |
| 25 | + """ |
| 26 | + Writes the list of dictionaries to a newline-delimited file |
| 27 | +
|
| 28 | + Args: |
| 29 | + obj (list[dict[str, Any]]): List of dictionaries to convert |
| 30 | + fp (IO): File pointer to write the string representation to |
| 31 | + **kwargs: Additional keyword arguments to pass to json.dumps |
| 32 | +
|
| 33 | + Returns: |
| 34 | + None |
| 35 | + """ |
| 36 | + # Indent breaks ndjson formatting |
| 37 | + kwargs["indent"] = None |
| 38 | + text = dumps(obj, **kwargs) |
| 39 | + fp.write(text) |
| 40 | + |
| 41 | + |
| 42 | +def loads(s: str, **kwargs) -> list[dict[str, Any]]: |
| 43 | + """ |
| 44 | + Converts the raw string into a list of dictionaries |
| 45 | +
|
| 46 | + Args: |
| 47 | + s (str): Raw string to convert |
| 48 | + **kwargs: Additional keyword arguments to pass to json.loads |
| 49 | +
|
| 50 | + Returns: |
| 51 | + list[dict[str, Any]]: List of dictionaries parsed from the input string |
| 52 | + """ |
| 53 | + return [json.loads(line, **kwargs) for line in s.splitlines()] |
| 54 | + |
| 55 | + |
| 56 | +def load(fp: IO, **kwargs) -> list[dict[str, Any]]: |
| 57 | + """ |
| 58 | + Converts the contents of the file into a list of dictionaries |
| 59 | +
|
| 60 | + Args: |
| 61 | + fp (IO): File pointer to read the string representation from |
| 62 | + **kwargs: Additional keyword arguments to pass to json.loads |
| 63 | +
|
| 64 | + Returns: |
| 65 | + list[dict[str, Any]]: List of dictionaries parsed from the file |
| 66 | + """ |
| 67 | + return loads(fp.read(), **kwargs) |
0 commit comments