datalad_next.itertools.load_json_with_flag

datalad_next.itertools.load_json_with_flag(iterable: Iterable[bytes | str]) Generator[tuple[Any | json.decoder.JSONDecodeError, bool], None, None][source]

Convert items from iterable into JSON objects and a success flag

load_json_with_flag works analogous to load_json, but reports success and failure differently.

On successful conversion to a JSON-object, load_json_with_flag will yield a tuple of two elements. The first element contains the JSON-object, the second element is True.

If the conversion to a JSON-object fails, load_json_with_flag will yield a tuple of two elements, where the first element contains the json.decoder.JSONDecodeError that was raised during conversion, and the second element is False:

>>> from datalad_next.itertools import load_json, load_json_with_flag
>>> tuple(load_json_with_flag(['{"b": 2}']))
(({'b': 2}, True),)
>>> tuple(load_json_with_flag(['{"d": 4']))   # Faulty JSON-encoding
((JSONDecodeError("Expecting ',' delimiter: line 1 column 8 (char 7)"), False),)
Parameters:

iterable (Iterable[bytes | str]) -- The iterable that yields the JSON-strings or -bytestrings that should be parsed and converted into JSON-objects

Yields:

tuple[Any | json.decoder.JSONDecodeError, bool] -- A tuple containing of a decoded JSON-object and True, if the JSON string could be decoded correctly. If the JSON string could not be decoded correctly, the tuple will contain the json.decoder.JSONDecodeError that was raised during JSON-decoding and False.