jsonype package
Module contents
- jsonype.FromBytes() ToJsonConverter[bytes][source]
Return a converter that converts objects of type
bytes.bytesare converted to a base64 encoded string.
- class jsonype.FromDataclass[source]
Bases:
ToJsonConverter[DataclassTarget_contra]Converts objects of
dataclasses.dataclass().A dataclass is converted to a
dictwith keys corresponding to the fields of the dataclass and values being converted with their respectiveToJsonConverter.- can_convert(o: Any) bool[source]
Return if this converter can convert the given object to an object representing JSON.
- Parameters:
o – the object to be converted to an object representing JSON
- Returns:
Trueif this converter can convert the given object into an object representing JSON,Falseotherwise.
- convert(o: DataclassTarget_contra, to_json: Callable[[Any], None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]]]) None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]][source]
Convert the given object of type
SourceType_contrato an object representing JSON.- Parameters:
o – the object to convert
to_json – If this converter converts container types like
typing.Sequencethis function is used to convert the contained objects into their corresponding objects representing JSON.
- Returns:
the converted object representing JSON.
- Raises:
ValueError – If the object cannot be converted to an object representing JSON.
- jsonype.FromDate() ToJsonConverter[date][source]
Return a converter that converts objects of type
datetime.date.A
dateis converted to its iso-string usingdatetime.date.isoformat()
- jsonype.FromDatetime() ToJsonConverter[datetime][source]
Return a converter that converts objects of type
datetime.datetime.A
datetimeis converted to its iso-string usingdatetime.datetime.isoformat()
- exception jsonype.FromJsonConversionError(js: None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]], path: JsonPath, target_type: type, reason: str | None = None)[source]
Bases:
ValueError
- class jsonype.FromJsonConverter[source]
Bases:
ABC,Generic[TargetType_co,ContainedTargetType_co]The base-class for converters that convert from objects representing JSON.
Converters that convert from objects representing JSON to their specific python object have to implement the two abstract methods defined in this base-class.
- TargetType:
The type this converter converts objects representing JSON to.
- ContainedTargetType:
If
TargetTypeis a container type (likeSequencefor example) this is the type of the objects the container contains (e.g. the type of the elements of aSequence).
- abstractmethod can_convert(js: None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]], target_type_info: ParameterizedTypeInfo[Any]) bool[source]
Return if this converts the given JSON representation into the given target-type.
- Parameters:
js – the object representing JSON to be converted
target_type_info – Describes the target-type of the conversion.
- Returns:
Trueif this converter can convertjsintotarget_type,Falseotherwise.
- abstractmethod convert(js: None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]], target_type_info: ParameterizedTypeInfo[TargetType_co], path: JsonPath, from_json: Callable[[None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]], type[ContainedTargetType_co], JsonPath], ContainedTargetType_co]) TargetType_co[source]
Convert the given object representing JSON to the given target type.
- Parameters:
js – the JSON-representation to convert
target_type_info – describes the type to convert to
path – the accumulated path where
jsstems from. If this is a top-level conversion the path is empty (JsonPath()) otherwise it denotes the JSON element where the fragmentjsis located in the JSON that was passed top-level, E.g. ifjsis the1in{"a": [1]}the path isJsonPath(("a", 0)).from_json – If this converter converts into container types like
typing.Sequencethis function is used to convert the contained JSON-nodes into their respective target-types.
- Returns:
the converted object of type
target_type- Raises:
ValueError – If the JSON-representation cannot be converted an instance of
target_type.
- class jsonype.FromMapping[source]
Bases:
ToJsonConverter[Mapping[str,Any]]Converts objects of type
typing.Mapping.A
typing.Mappingwithstrtyped keys is converted to adictwith all values being converted with their respectiveToJsonConverter.- can_convert(o: Any) bool[source]
Return if this converter can convert the given object to an object representing JSON.
- Parameters:
o – the object to be converted to an object representing JSON
- Returns:
Trueif this converter can convert the given object into an object representing JSON,Falseotherwise.
- convert(o: Mapping[str, Any], to_json: Callable[[Any], None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]]]) None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]][source]
Convert the given object of type
typing.Mappingto an object representing JSON.- Raises:
ValueError – If the
typing.Mappingcontains none-strkeys.
- class jsonype.FromNamedTuple[source]
Bases:
ToJsonConverter[NamedTupleSource_contra]Converts objects of type
typing.NamedTuple.A
typing.NamedTupleis converted to adictwith keys corresponding to the fields of theNamedTupleand values being converted with their respectiveToJsonConverter.- can_convert(o: Any) bool[source]
Return if this converter can convert the given object to an object representing JSON.
- Parameters:
o – the object to be converted to an object representing JSON
- Returns:
Trueif this converter can convert the given object into an object representing JSON,Falseotherwise.
- convert(o: NamedTupleSource_contra, to_json: Callable[[Any], None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]]]) None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]][source]
Convert the given object of type
SourceType_contrato an object representing JSON.- Parameters:
o – the object to convert
to_json – If this converter converts container types like
typing.Sequencethis function is used to convert the contained objects into their corresponding objects representing JSON.
- Returns:
the converted object representing JSON.
- Raises:
ValueError – If the object cannot be converted to an object representing JSON.
- class jsonype.FromNone[source]
Bases:
ToJsonConverter[None]Converts a
Noneinstance.A
Noneis converted toNone.- can_convert(o: Any) bool[source]
Return if this converter can convert the given object to an object representing JSON.
- Parameters:
o – the object to be converted to an object representing JSON
- Returns:
Trueif this converter can convert the given object into an object representing JSON,Falseotherwise.
- convert(o: None, to_json: Callable[[Any], None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]]]) None[source]
Convert the given object of type
SourceType_contrato an object representing JSON.- Parameters:
o – the object to convert
to_json – If this converter converts container types like
typing.Sequencethis function is used to convert the contained objects into their corresponding objects representing JSON.
- Returns:
the converted object representing JSON.
- Raises:
ValueError – If the object cannot be converted to an object representing JSON.
- jsonype.FromPath() ToJsonConverter[Path][source]
Return a converter that converts objects of type
pathlib.Path.A
Pathis converted to a string usingstr.
- class jsonype.FromSequence[source]
Bases:
ToJsonConverter[Sequence[Any]]Converts objects of type
typing.Sequence.A
typing.Sequenceis converted to alistwith all elements being converted with their respectiveToJsonConverter.- can_convert(o: Any) bool[source]
Return if this converter can convert the given object to an object representing JSON.
- Parameters:
o – the object to be converted to an object representing JSON
- Returns:
Trueif this converter can convert the given object into an object representing JSON,Falseotherwise.
- convert(o: Sequence[Any], to_json: Callable[[Any], None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]]]) None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]][source]
Convert the given object of type
SourceType_contrato an object representing JSON.- Parameters:
o – the object to convert
to_json – If this converter converts container types like
typing.Sequencethis function is used to convert the contained objects into their corresponding objects representing JSON.
- Returns:
the converted object representing JSON.
- Raises:
ValueError – If the object cannot be converted to an object representing JSON.
- class jsonype.FromSimple[source]
Bases:
ToJsonConverter[int|float|str|bool]Converts simple objects of type
int,float,str,bool.The conversion simply returns the given object.
- can_convert(o: Any) bool[source]
Return if this converter can convert the given object to an object representing JSON.
- Parameters:
o – the object to be converted to an object representing JSON
- Returns:
Trueif this converter can convert the given object into an object representing JSON,Falseotherwise.
- convert(o: int | float | str | bool, to_json: Callable[[Any], None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]]]) int | float | str | bool[source]
Convert the given object of type
SourceType_contrato an object representing JSON.- Parameters:
o – the object to convert
to_json – If this converter converts container types like
typing.Sequencethis function is used to convert the contained objects into their corresponding objects representing JSON.
- Returns:
the converted object representing JSON.
- Raises:
ValueError – If the object cannot be converted to an object representing JSON.
- jsonype.FromTime() ToJsonConverter[time][source]
Return a converter that converts objects of type
datetime.time.A
timeis converted to its iso-string usingdatetime.time.isoformat()
- jsonype.FromUUID() ToJsonConverter[UUID][source]
Return a converter that converts objects of type
uuid.UUID.An
UUIDis converted to its 8-4-4-4-12 format usingstr.
- jsonype.FromUrl() ToJsonConverter[SplitResult][source]
Return a converter that converts objects of type
urllib.parse.SplitResult.A
SplitResultis converted byurllib.parse.urlunsplit().
- class jsonype.FunctionBasedFromSimpleJsonConverter(f: Callable[[JsonType_contra], TargetType_co], input_type: type[JsonType_contra] | None = None, output_type: type[TargetType_co] | None = None)[source]
Bases:
FromJsonConverter[TargetType_co,None]A function based
FromJsonConverter.Creates a
FromJsonConverterfrom a function that maps a simple JSON type to a target type.- Parameters:
f – A function that maps a simple JSON type (int, float, str, bool) into a target type.
input_type – None, if the JSON type can be derived from the function signature (using
inspect.signature()) or the concrete simple JSON type if this is not possible.output_type – None if the target type can be derived from the function signature (using
inspect.signature()) or the concrete target type if this is not possible.FunctionBasedFromSimpleJsonConverter (Example) –
>>> from typing import Sequence >>> from jsonype import (FunctionBasedFromSimpleJsonConverter, ParameterizedTypeInfo, ... JsonPath) >>> >>> def str_to_list(comma_separated_str: str) -> Sequence[str]: ... return comma_separated_str.split(",") >>> >>> converter = FunctionBasedFromSimpleJsonConverter(str_to_list) >>> print(converter.convert( ... "a,b", ... ParameterizedTypeInfo.from_optionally_generic(Sequence[str]), ... JsonPath(), ... lambda a, b, c: None ... )) ['a', 'b'] >>> # if the function signature is untyped, types can be provided explicitly: >>> >>> converter2 = FunctionBasedFromSimpleJsonConverter( ... lambda s: s.split(","), str, Sequence[str])
- __init__(f: Callable[[JsonType_contra], TargetType_co], input_type: type[JsonType_contra] | None = None, output_type: type[TargetType_co] | None = None) None[source]
- can_convert(js: None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]], target_type_info: ParameterizedTypeInfo[Any]) bool[source]
Return if this converts the given JSON representation into the given target-type.
- Parameters:
js – the object representing JSON to be converted
target_type_info – Describes the target-type of the conversion.
- Returns:
Trueif this converter can convertjsintotarget_type,Falseotherwise.
- convert(js: None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]], target_type_info: ParameterizedTypeInfo[TargetType_co], path: JsonPath, _from_json: Callable[[None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]], type[ContainedTargetType_co], JsonPath], ContainedTargetType_co]) TargetType_co[source]
Convert the given object representing JSON to the given target type.
- Parameters:
js – the JSON-representation to convert
target_type_info – describes the type to convert to
path – the accumulated path where
jsstems from. If this is a top-level conversion the path is empty (JsonPath()) otherwise it denotes the JSON element where the fragmentjsis located in the JSON that was passed top-level, E.g. ifjsis the1in{"a": [1]}the path isJsonPath(("a", 0)).from_json – If this converter converts into container types like
typing.Sequencethis function is used to convert the contained JSON-nodes into their respective target-types.
- Returns:
the converted object of type
target_type- Raises:
ValueError – If the JSON-representation cannot be converted an instance of
target_type.
- class jsonype.FunctionBasedToSimpleJsonConverter(f: Callable[[SourceType_contra], JsonType_co], input_type: type[SourceType_contra] | None = None)[source]
Bases:
ToJsonConverter[SourceType_contra]A function based
ToJsonConverter.Creates a
ToJsonConverterfrom a function that maps a source type to a simple JSON type.- Parameters:
f – A function that maps a source type into a simple JSON type (int, float, str, bool).
input_type – None, if the source type can be derived from the function signature (using
inspect.signature()) or the concrete source type if this is not possible.
- Example FunctionBasedToSimpleJsonConverter:
>>> from typing import Sequence >>> from jsonype import FunctionBasedToSimpleJsonConverter >>> >>> def abbreviate_str(s: str) -> str: ... return s if len(s) < 8 else f"{s[:2]}...{s[-2:]}" >>> >>> converter = FunctionBasedToSimpleJsonConverter(abbreviate_str) >>> print(converter.convert( ... "Long String", ... lambda a: None ... )) Lo...ng >>> # if the function signature is untyped, the input type can be provided explicitly: >>> >>> converter2 = FunctionBasedToSimpleJsonConverter( ... lambda s: s if len(s) < 8 else f"{s[:2]}...{s[-2:]}", str)
- __init__(f: Callable[[SourceType_contra], JsonType_co], input_type: type[SourceType_contra] | None = None) None[source]
- can_convert(o: Any) bool[source]
Return if this converter can convert the given object to an object representing JSON.
- Parameters:
o – the object to be converted to an object representing JSON
- Returns:
Trueif this converter can convert the given object into an object representing JSON,Falseotherwise.
- convert(o: SourceType_contra, _to_json: Callable[[Any], None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]]]) None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]][source]
Convert the given object of type
SourceType_contrato an object representing JSON.- Parameters:
o – the object to convert
to_json – If this converter converts container types like
typing.Sequencethis function is used to convert the contained objects into their corresponding objects representing JSON.
- Returns:
the converted object representing JSON.
- Raises:
ValueError – If the object cannot be converted to an object representing JSON.
- class jsonype.JsonPath(_elements: tuple[str | int, ...] = ())[source]
Bases:
objectRepresent the path to an element in a nested JSON structure.
The string representation of this path follows the ideas of JSONPath .
- class jsonype.ParameterizedTypeInfo(full_type: type[TargetType_co], origin_of_generic: type | None, annotations: Mapping[str, type], generic_args: Sequence[type])[source]
Bases:
Generic[TargetType_co]Information about a parameterized type.
- Parameters:
full_type – full type information, for example
Mapping[str, int].origin_of_generic – the unsubscripted version of
full_type(i.e. without its type parameters), for exampleMapping.Noneiffull_typeis not a generic type. Can be computed withtyping.get_origin().annotations – a mapping from member name to its type. Can be computed with :func:
typing.get_annotations.generic_args – just the arguments of the generic type as a tuple, for example
(str, int).()iffull_typeis not a generic type. Can be computed withtyping.get_args().
- __init__(full_type: type[TargetType_co], origin_of_generic: type | None, annotations: Mapping[str, type], generic_args: Sequence[type]) None
- classmethod from_optionally_generic(t: type[TargetType_co]) ParameterizedTypeInfo[TargetType_co][source]
- class jsonype.ToAny[source]
Bases:
FromJsonConverter[Any,None]Convert to the target type
typing.Any.This converter returns the object representing JSON unchanged.
- can_convert(_js: None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]], target_type_info: ParameterizedTypeInfo[Any]) bool[source]
Return if this converts the given JSON representation into the given target-type.
- Parameters:
js – the object representing JSON to be converted
target_type_info – Describes the target-type of the conversion.
- Returns:
Trueif this converter can convertjsintotarget_type,Falseotherwise.
- convert(js: None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]], target_type_info: ParameterizedTypeInfo[Any], path: JsonPath, from_json: Callable[[None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]], type[None], JsonPath], None]) Any[source]
Convert the given object representing JSON to the given target type.
- Parameters:
js – the JSON-representation to convert
target_type_info – describes the type to convert to
path – the accumulated path where
jsstems from. If this is a top-level conversion the path is empty (JsonPath()) otherwise it denotes the JSON element where the fragmentjsis located in the JSON that was passed top-level, E.g. ifjsis the1in{"a": [1]}the path isJsonPath(("a", 0)).from_json – If this converter converts into container types like
typing.Sequencethis function is used to convert the contained JSON-nodes into their respective target-types.
- Returns:
the converted object of type
target_type- Raises:
ValueError – If the JSON-representation cannot be converted an instance of
target_type.
- jsonype.ToBytes() FromJsonConverter[bytes, None][source]
Return a converter that converts a JSON string to
bytes.The JSON string is expected to be in a base64 encoded string otherwise the conversion raises a
FromJsonConversionError.
- class jsonype.ToDataclass(strict: bool = False)[source]
Bases:
FromJsonConverter[DataclassTarget_co,TargetType_co]Convert an object representing JSON to a
dataclasses.dataclass().The JSON object is expected to have keys corresponding to the fields of the dataclass. Each value is converted to the corresponding field type.
- can_convert(_js: None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]], target_type_info: ParameterizedTypeInfo[Any]) bool[source]
Return if this converts the given JSON representation into the given target-type.
- Parameters:
js – the object representing JSON to be converted
target_type_info – Describes the target-type of the conversion.
- Returns:
Trueif this converter can convertjsintotarget_type,Falseotherwise.
- convert(js: None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]], target_type_info: ParameterizedTypeInfo[DataclassTarget_co], path: JsonPath, from_json: Callable[[None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]], type, JsonPath], ContainedTargetType_co]) DataclassTarget_co[source]
Convert the given object representing JSON to the given target type.
- Parameters:
js – the JSON-representation to convert
target_type_info – describes the type to convert to
path – the accumulated path where
jsstems from. If this is a top-level conversion the path is empty (JsonPath()) otherwise it denotes the JSON element where the fragmentjsis located in the JSON that was passed top-level, E.g. ifjsis the1in{"a": [1]}the path isJsonPath(("a", 0)).from_json – If this converter converts into container types like
typing.Sequencethis function is used to convert the contained JSON-nodes into their respective target-types.
- Returns:
the converted object of type
target_type- Raises:
ValueError – If the JSON-representation cannot be converted an instance of
target_type.
- jsonype.ToDate() FromJsonConverter[date, None][source]
Return a converter that converts a JSON string to a
datetime.date.The JSON string is expected to be in ISO-format (as generated by
datetime.date.isoformat()), otherwise the conversion raises aFromJsonConversionError
- jsonype.ToDatetime() FromJsonConverter[datetime, None][source]
Return a converter that converts a JSON string to a
datetime.datetime.The JSON string is expected to be in ISO-format (as generated by
datetime.datetime.isoformat()), otherwise the conversion raises aFromJsonConversionError
- exception jsonype.ToJsonConversionError(o: Any, reason: str | None = None)[source]
Bases:
ValueError
- class jsonype.ToJsonConverter[source]
Bases:
ABC,Generic[SourceType_contra]The base-class for converters that convert to objects representing JSON.
Converters that convert objects of their specific type
Tto objects representing JSON have to implement the two abstract methods defined in this base-class.- SourceType_contra:
The type of the object that shall be converted into an object representing JSON.
- abstractmethod can_convert(o: Any) bool[source]
Return if this converter can convert the given object to an object representing JSON.
- Parameters:
o – the object to be converted to an object representing JSON
- Returns:
Trueif this converter can convert the given object into an object representing JSON,Falseotherwise.
- abstractmethod convert(o: SourceType_contra, to_json: Callable[[Any], None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]]]) None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]][source]
Convert the given object of type
SourceType_contrato an object representing JSON.- Parameters:
o – the object to convert
to_json – If this converter converts container types like
typing.Sequencethis function is used to convert the contained objects into their corresponding objects representing JSON.
- Returns:
the converted object representing JSON.
- Raises:
ValueError – If the object cannot be converted to an object representing JSON.
- class jsonype.ToList[source]
Bases:
FromJsonConverter[Sequence[TargetType_co],TargetType_co]Convert an array to a
typing.Sequence.Convert all elements of the array into the corresponding target type given by the type-parameter of the
typing.Sequence.A target type of
Sequence[int]can convert alistofint, but not alistofstr.- can_convert(js: None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]], target_type_info: ParameterizedTypeInfo[Any]) bool[source]
Return if this converts the given JSON representation into the given target-type.
- Parameters:
js – the object representing JSON to be converted
target_type_info – Describes the target-type of the conversion.
- Returns:
Trueif this converter can convertjsintotarget_type,Falseotherwise.
- convert(js: None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]], target_type_info: ParameterizedTypeInfo[Sequence[TargetType_co]], path: JsonPath, from_json: Callable[[None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]], type[TargetType_co], JsonPath], TargetType_co]) Sequence[TargetType_co][source]
Convert the given object representing JSON to the given target type.
- Parameters:
js – the JSON-representation to convert
target_type_info – describes the type to convert to
path – the accumulated path where
jsstems from. If this is a top-level conversion the path is empty (JsonPath()) otherwise it denotes the JSON element where the fragmentjsis located in the JSON that was passed top-level, E.g. ifjsis the1in{"a": [1]}the path isJsonPath(("a", 0)).from_json – If this converter converts into container types like
typing.Sequencethis function is used to convert the contained JSON-nodes into their respective target-types.
- Returns:
the converted object of type
target_type- Raises:
ValueError – If the JSON-representation cannot be converted an instance of
target_type.
- class jsonype.ToLiteral[source]
Bases:
FromJsonConverter[TargetType_co,None]Convert to one of the listed literals.
Returns the JSON-representation unchanged if it equals one of the literals.
A
target_typelikeLiteral[5, 6]can be used to convert for example a5or a6, but not a7.- can_convert(js: None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]], target_type_info: ParameterizedTypeInfo[Any]) bool[source]
Return if this converts the given JSON representation into the given target-type.
- Parameters:
js – the object representing JSON to be converted
target_type_info – Describes the target-type of the conversion.
- Returns:
Trueif this converter can convertjsintotarget_type,Falseotherwise.
- convert(js: None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]], target_type_info: ParameterizedTypeInfo[TargetType_co], path: JsonPath, from_json: Callable[[None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]], type[None], JsonPath], None]) TargetType_co[source]
Convert the given object representing JSON to the given target type.
- Parameters:
js – the JSON-representation to convert
target_type_info – describes the type to convert to
path – the accumulated path where
jsstems from. If this is a top-level conversion the path is empty (JsonPath()) otherwise it denotes the JSON element where the fragmentjsis located in the JSON that was passed top-level, E.g. ifjsis the1in{"a": [1]}the path isJsonPath(("a", 0)).from_json – If this converter converts into container types like
typing.Sequencethis function is used to convert the contained JSON-nodes into their respective target-types.
- Returns:
the converted object of type
target_type- Raises:
ValueError – If the JSON-representation cannot be converted an instance of
target_type.
- class jsonype.ToMapping[source]
Bases:
FromJsonConverter[Mapping[str,TargetType_co],TargetType_co]Convert the JSON-representation to a
typing.Mapping.Convert all entries of the given
Mapping(respectively JSON-object) into entries of aMappingwith the given key and value target types.A target type of
Mapping[str, int]can convert for example{ "key1": 1, "key2": 2 }.- can_convert(js: None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]], target_type_info: ParameterizedTypeInfo[Any]) bool[source]
Return if this converts the given JSON representation into the given target-type.
- Parameters:
js – the object representing JSON to be converted
target_type_info – Describes the target-type of the conversion.
- Returns:
Trueif this converter can convertjsintotarget_type,Falseotherwise.
- convert(js: None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]], target_type_info: ParameterizedTypeInfo[Mapping[str, TargetType_co]], path: JsonPath, from_json: Callable[[None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]], type[TargetType_co], JsonPath], TargetType_co]) Mapping[str, TargetType_co][source]
Convert the given object representing JSON to the given target type.
- Parameters:
js – the JSON-representation to convert
target_type_info – describes the type to convert to
path – the accumulated path where
jsstems from. If this is a top-level conversion the path is empty (JsonPath()) otherwise it denotes the JSON element where the fragmentjsis located in the JSON that was passed top-level, E.g. ifjsis the1in{"a": [1]}the path isJsonPath(("a", 0)).from_json – If this converter converts into container types like
typing.Sequencethis function is used to convert the contained JSON-nodes into their respective target-types.
- Returns:
the converted object of type
target_type- Raises:
ValueError – If the JSON-representation cannot be converted an instance of
target_type.
- class jsonype.ToNamedTuple(strict: bool = False)[source]
Bases:
FromJsonConverter[NamedTupleTarget_co,TargetType_co]Convert an object representing JSON to a
typing.NamedTuple.The JSON object is expected to have keys corresponding to the
NamedTuplefields. Each value is converted to the corresponding field type. In case of an untypedNamedTuple, the field type is assumed to beAny.- can_convert(_js: None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]], target_type_info: ParameterizedTypeInfo[Any]) bool[source]
Return if this converts the given JSON representation into the given target-type.
- Parameters:
js – the object representing JSON to be converted
target_type_info – Describes the target-type of the conversion.
- Returns:
Trueif this converter can convertjsintotarget_type,Falseotherwise.
- convert(js: None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]], target_type_info: ParameterizedTypeInfo[NamedTupleTarget_co], path: JsonPath, from_json: Callable[[None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]], type[TargetType_co], JsonPath], TargetType_co]) NamedTupleTarget_co[source]
Convert the given object representing JSON to the given target type.
- Parameters:
js – the JSON-representation to convert
target_type_info – describes the type to convert to
path – the accumulated path where
jsstems from. If this is a top-level conversion the path is empty (JsonPath()) otherwise it denotes the JSON element where the fragmentjsis located in the JSON that was passed top-level, E.g. ifjsis the1in{"a": [1]}the path isJsonPath(("a", 0)).from_json – If this converter converts into container types like
typing.Sequencethis function is used to convert the contained JSON-nodes into their respective target-types.
- Returns:
the converted object of type
target_type- Raises:
ValueError – If the JSON-representation cannot be converted an instance of
target_type.
- class jsonype.ToNone[source]
Bases:
FromJsonConverter[None,None]Return the JSON-representation, if it is
None.- can_convert(js: None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]], target_type_info: ParameterizedTypeInfo[Any]) bool[source]
Return if this converts the given JSON representation into the given target-type.
- Parameters:
js – the object representing JSON to be converted
target_type_info – Describes the target-type of the conversion.
- Returns:
Trueif this converter can convertjsintotarget_type,Falseotherwise.
- convert(js: None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]], target_type_info: ParameterizedTypeInfo[Any], path: JsonPath, from_json: Callable[[None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]], type[None], JsonPath], None]) None[source]
Convert the given object representing JSON to the given target type.
- Parameters:
js – the JSON-representation to convert
target_type_info – describes the type to convert to
path – the accumulated path where
jsstems from. If this is a top-level conversion the path is empty (JsonPath()) otherwise it denotes the JSON element where the fragmentjsis located in the JSON that was passed top-level, E.g. ifjsis the1in{"a": [1]}the path isJsonPath(("a", 0)).from_json – If this converter converts into container types like
typing.Sequencethis function is used to convert the contained JSON-nodes into their respective target-types.
- Returns:
the converted object of type
target_type- Raises:
ValueError – If the JSON-representation cannot be converted an instance of
target_type.
- jsonype.ToPath() FromJsonConverter[Path, None][source]
Return a converter that converts a JSON string to a
pathlib.Path.The JSON string is expected to be in a format parseable by
pathlib.Path, otherwise the conversion raises aFromJsonConversionError
- class jsonype.ToSimple[source]
Bases:
FromJsonConverter[TargetType_co,None]Return the JSON-representation, if it is one of the types
int, float, str, bool.- can_convert(js: None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]], target_type_info: ParameterizedTypeInfo[Any]) bool[source]
Return if this converts the given JSON representation into the given target-type.
- Parameters:
js – the object representing JSON to be converted
target_type_info – Describes the target-type of the conversion.
- Returns:
Trueif this converter can convertjsintotarget_type,Falseotherwise.
- convert(js: None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]], target_type_info: ParameterizedTypeInfo[TargetType_co], path: JsonPath, from_json: Callable[[None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]], type[None], JsonPath], None]) TargetType_co[source]
Convert the given object representing JSON to the given target type.
- Parameters:
js – the JSON-representation to convert
target_type_info – describes the type to convert to
path – the accumulated path where
jsstems from. If this is a top-level conversion the path is empty (JsonPath()) otherwise it denotes the JSON element where the fragmentjsis located in the JSON that was passed top-level, E.g. ifjsis the1in{"a": [1]}the path isJsonPath(("a", 0)).from_json – If this converter converts into container types like
typing.Sequencethis function is used to convert the contained JSON-nodes into their respective target-types.
- Returns:
the converted object of type
target_type- Raises:
ValueError – If the JSON-representation cannot be converted an instance of
target_type.
- jsonype.ToTime() FromJsonConverter[time, None][source]
Return a converter that converts a JSON string to a
datetime.time.The JSON string is expected to be in ISO-format (as generated by
datetime.time.isoformat()), otherwise the conversion raises aFromJsonConversionError
- class jsonype.ToTuple[source]
Bases:
FromJsonConverter[tuple[Any, …],Any]Convert an array to a
tuple.Convert the elements of the array in the corresponding target type given by the type-parameter of the
tuplein the same position as the element. RaisesValueErrorif the number of type-parameters do not match to the number of elements.The type-parameters may contain a single
...which is replaced by as manyAnysuch that the number of type-parameters equals the number of elements. So a target type oftuple[int, ..., str]is equivalent to a target type oftuple[int, Any, Any, Any, str]if the JSON-representation to be converted is atyping.Sequenceof 5 elements.A target type like
tuple[int, str]can convert for example the list[5, "Hello World!"]into the tuple(5, "Hello World!"), but not["Hello World!", 5]- can_convert(js: None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]], target_type_info: ParameterizedTypeInfo[Any]) bool[source]
Return if this converts the given JSON representation into the given target-type.
- Parameters:
js – the object representing JSON to be converted
target_type_info – Describes the target-type of the conversion.
- Returns:
Trueif this converter can convertjsintotarget_type,Falseotherwise.
- convert(js: None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]], target_type_info: ParameterizedTypeInfo[tuple[Any, ...]], path: JsonPath, from_json: Callable[[None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]], type[Any], JsonPath], Any]) tuple[Any, ...][source]
Convert the given object representing JSON to the given target type.
- Parameters:
js – the JSON-representation to convert
target_type_info – describes the type to convert to
path – the accumulated path where
jsstems from. If this is a top-level conversion the path is empty (JsonPath()) otherwise it denotes the JSON element where the fragmentjsis located in the JSON that was passed top-level, E.g. ifjsis the1in{"a": [1]}the path isJsonPath(("a", 0)).from_json – If this converter converts into container types like
typing.Sequencethis function is used to convert the contained JSON-nodes into their respective target-types.
- Returns:
the converted object of type
target_type- Raises:
ValueError – If the JSON-representation cannot be converted an instance of
target_type.
- class jsonype.ToTypedMapping(strict: bool = False)[source]
Bases:
FromJsonConverter[Mapping[str,TargetType_co],TargetType_co]Convert the JSON-representation to a
typing.TypedDict.Convert all entries of the given
Mepping(respectively JSON-object) into entries of aTypedDictwith the given key and value target types.- Parameters:
strict – indicates if the conversion of a
Mappingshould fail, if it contains more keys than the provided target type. PassTrueto make it fail in this case. Defaults toFalse.
Example
>>> from typing import TypedDict >>> >>> # using the ToTypedMapping converter one can convert for example: >>> json_object = {"k1": 1.0, "k2": 2, "unknown-key": "value"} >>> # into the following: >>> class Map(TypedDict): ... k1: float ... k2: int >>> # In this example the result will meet: >>> # assert result == {"k1": 1.0, "k2": 2}
- can_convert(js: None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]], target_type_info: ParameterizedTypeInfo[Any]) bool[source]
Return if this converts the given JSON representation into the given target-type.
- Parameters:
js – the object representing JSON to be converted
target_type_info – Describes the target-type of the conversion.
- Returns:
Trueif this converter can convertjsintotarget_type,Falseotherwise.
- convert(js: None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]], target_type_info: ParameterizedTypeInfo[Mapping[str, TargetType_co]], path: JsonPath, from_json: Callable[[None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]], type[TargetType_co], JsonPath], TargetType_co]) Mapping[str, TargetType_co][source]
Convert the given object representing JSON to the given target type.
- Parameters:
js – the JSON-representation to convert
target_type_info – describes the type to convert to
path – the accumulated path where
jsstems from. If this is a top-level conversion the path is empty (JsonPath()) otherwise it denotes the JSON element where the fragmentjsis located in the JSON that was passed top-level, E.g. ifjsis the1in{"a": [1]}the path isJsonPath(("a", 0)).from_json – If this converter converts into container types like
typing.Sequencethis function is used to convert the contained JSON-nodes into their respective target-types.
- Returns:
the converted object of type
target_type- Raises:
ValueError – If the JSON-representation cannot be converted an instance of
target_type.
- jsonype.ToUUID() FromJsonConverter[UUID, None][source]
Return a converter that converts a JSON string to a
uuid.UUID.The JSON string is expected to be in a format parseable by
uuid.UUID, otherwise the conversion raises aFromJsonConversionError
- class jsonype.ToUnion[source]
Bases:
FromJsonConverter[TargetType_co,TargetType_co]Convert to one of the type-parameters of the given
typing.Union.It tries to convert the object representing JSON to one of the type-parameters of the
Union-type in the order of their occurrence and returns the first successful conversion result. If none is successful it raises aValueError.A
target_typelikeUnion[int, str]can be used to convert for example a5or a"Hello World!", but will fail to convert alist.- can_convert(_js: None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]], target_type_info: ParameterizedTypeInfo[Any]) bool[source]
Return if this converts the given JSON representation into the given target-type.
- Parameters:
js – the object representing JSON to be converted
target_type_info – Describes the target-type of the conversion.
- Returns:
Trueif this converter can convertjsintotarget_type,Falseotherwise.
- convert(js: None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]], target_type_info: ParameterizedTypeInfo[TargetType_co], path: JsonPath, from_json: Callable[[None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]], type[TargetType_co], JsonPath], TargetType_co]) TargetType_co[source]
Convert the given object representing JSON to the given target type.
- Parameters:
js – the JSON-representation to convert
target_type_info – describes the type to convert to
path – the accumulated path where
jsstems from. If this is a top-level conversion the path is empty (JsonPath()) otherwise it denotes the JSON element where the fragmentjsis located in the JSON that was passed top-level, E.g. ifjsis the1in{"a": [1]}the path isJsonPath(("a", 0)).from_json – If this converter converts into container types like
typing.Sequencethis function is used to convert the contained JSON-nodes into their respective target-types.
- Returns:
the converted object of type
target_type- Raises:
ValueError – If the JSON-representation cannot be converted an instance of
target_type.
- jsonype.ToUrl() FromJsonConverter[SplitResult, None][source]
Return a converter that converts a JSON string to
urllib.parse.SplitResult.The JSON string is expected to be a URL that can be parsed with
urllib.parse.urlsplit()otherwise the conversion raises aFromJsonConversionError.
- class jsonype.TypedJson(from_json_converters: Sequence[FromJsonConverter[Any, Any]], to_json_converters: Sequence[ToJsonConverter[Any]])[source]
Bases:
objectProvides methods to convert python objects to/from a JSON-representation.
- Args;
- strict: Perform a strict from-JSON conversion.
This makes
from_json()raise more often for example when extra fields are in the JSON-representation that do not exist in the target-type.
- Example: TypedJson
>>> from dataclasses import dataclass >>> from typing import NamedTuple >>> from jsonype import TypedJson, FromJsonConversionError, JsonPath >>> from json import dumps, loads >>> >>> # Create TypedJson instance >>> typed_json = TypedJson.default() >>> >>> # Define your types with type-hints >>> class Address(NamedTuple): ... street: str ... city: str ... some_related_number: int >>> >>> @dataclass ... class Person: ... name: str ... address: Address >>> >>> # Parse JSON string with python's json package >>> js = loads('''{ ... "name": "John Doe", ... "address": { ... "street": "123 Maple Street", ... "city": "Any town", ... "some_related_number": 5, ... "zip": "ignored" ... } ... }''') >>> # convert generic representation to your type >>> person = typed_json.from_json(js, Person) >>> >>> assert person == Person( ... name="John Doe", ... address=Address( ... street="123 Maple Street", ... city="Any town", ... some_related_number=5 ... ), ... ) >>> >>> try: ... # strict conversion does not accept extra fields in the JSON-object ... person = TypedJson.default(strict=True).from_json(js, Person) ... except FromJsonConversionError as e: ... print(e) ("Cannot convert {'street': '...', ..., 'zip': 'ignored'} (type: <class 'dict'>) at $.address to <class 'Address'>: unexpected keys: {'zip'}", ... >>> >>> # JSON-types must match expected types: >>> # FromJsonConversionError contains path where the error occurred. >>> js = loads('''{ ... "name": "John Doe", ... "address": { ... "street": "123 Maple Street", ... "city": "Any town", ... "some_related_number": "5" ... } ... }''') >>> try: ... person = typed_json.from_json(js, Person) ... except FromJsonConversionError as e: ... print(e) ... assert e.path == JsonPath(("address", "some_related_number")) ("Cannot convert 5 (type: <class 'str'>) at $.address.some_related_number to <class 'int'>...", ... >>> # Convert typed objects to JSON >>> print(dumps(typed_json.to_json(person), indent=2)) { "name": "John Doe", "address": { "street": "123 Maple Street", "city": "Any town", "some_related_number": 5 } }
- __init__(from_json_converters: Sequence[FromJsonConverter[Any, Any]], to_json_converters: Sequence[ToJsonConverter[Any]]) None[source]
- append(from_json_converters: Sequence[FromJsonConverter[Any, Any]], to_json_converters: Sequence[ToJsonConverter[Any]]) TypedJson[source]
Return a new
TypedJsonwith the given converters appended to the existing ones.Existing converters take precedence over appended ones, i.e. if an appended converter converts the same types as an existing one (but differently), the appended one becomes ineffective.
- Parameters:
from_json_converters – a list of
FromJsonConverterthat are added to the top of the list of allFromJsonConverter.to_json_converters – a list of
ToJsonConverterthat are added to the top of the list of allToJsonConverter.
- Example append:
>>> from dataclasses import dataclass >>> from typing import Callable, Any >>> from jsonype import (TypedJson, FromJsonConversionError, FromJsonConverter, ... JsonPath, Json, ParameterizedTypeInfo) >>> from json import dumps, loads >>> >>> # A custom type that needs a custom converter >>> class CustomType: ... def __eq__(self, other: Any) -> bool: ... return type(other) == CustomType >>> >>> @dataclass ... class Person: ... name: str ... something_special: CustomType >>> >>> js = loads('''{ ... "name": "John Doe", ... "something_special": "CustomType" ... }''') >>> typed_json = TypedJson.default() >>> # Without custom converter the conversion fails >>> try: ... person = typed_json.from_json(js, Person) ... except FromJsonConversionError as e: ... print(e) ("Cannot convert CustomType (type: <class 'str'>) at $.something_special to <class 'CustomType'>: No suitable converter registered. Use TypedJson.append or TypedJson.prepend to register one.", ... >>> # Let's write a custom converter that can convert the String "CustomType" to >>> # an instance of the CustomType ... >>> class StringToCustomType(FromJsonConverter[CustomType, None]): ... ... def can_convert( ... self, js: Json, target_type_info: ParameterizedTypeInfo[Any] ... ) -> bool: ... return (js == CustomType.__name__ ... and target_type_info.full_type is CustomType) ... ... def convert(self, js: Json, target_type_info: ParameterizedTypeInfo[CustomType], ... path: JsonPath, ... from_json: Callable[[Json, type[None], JsonPath], ... None] ... ) -> CustomType: ... return CustomType() >>> >>> # ... and create a new TypedJson instance with the converter appended. >>> typed_json = typed_json.append([StringToCustomType()], []) >>> person = typed_json.from_json(js, Person) >>> assert person == Person("John Doe", CustomType())
- classmethod default(strict: bool = False) TypedJson[source]
Create a
TypedJsoninstance with reasonable default converters.Next to straight forward converters for simple types (
str, bool, ...) and simple collections (list, tuple, Mapping) the converters support the following conversions:dataclasses.dataclassto/fromdicttyping.NamedTupleto/fromdictvarious time-related types like
datetime.datetimeto/fromstr
The full list of converters is:
- Parameters:
strict – Some of the converters support a strict-mode. For example the converters converting to a
dataclassor aNamedTuplefail in struct mode if the JSON object contains additional keys.
- static default_converters(strict: bool = False) tuple[Sequence[FromJsonConverter[Any, Any]], Sequence[ToJsonConverter[Any]]][source]
- from_json(js: None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]], target_type: type[TargetType]) TargetType[source]
Convert the given JSON-representation to an object of the given type.
The JSON-representation is typically generated from a JSON string by using
json.loads().- Parameters:
js – the JSON-representation to be converted
target_type – the type the JSON-representation should be converted to
- Returns:
the object of the given type
- Raises:
ValueError – If the JSON-representation cannot be converted as a converter fails to convert it to an object of the required type.
- from_json_with_path(js: None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]], target_type: type[TargetType], path: JsonPath) TargetType[source]
- prepend(from_json_converters: Sequence[FromJsonConverter[Any, Any]], to_json_converters: Sequence[ToJsonConverter[Any]]) TypedJson[source]
Return a new
TypedJsonwith the given converters prepended to the existing ones.Prepended converters take precedence over existing ones, i.e. if a prepended converter converts the same types as an existing one (but differently), the existing one becomes ineffective. In case of a
FromJsonConverterboth input and output types are considered.- Parameters:
from_json_converters – a list of
FromJsonConverterthat are added to the top of the list of allFromJsonConverter.to_json_converters – a list of
ToJsonConverterthat are added to the top of the list of allToJsonConverter.
- Example prepend:
>>> from dataclasses import dataclass >>> from jsonype import TypedJson, FunctionBasedToSimpleJsonConverter >>> from json import dumps >>> >>> class Password(str): ... pass >>> >>> @dataclass ... class Person: ... name: str ... pwd: Password >>> >>> person = Person("John Doe", Password("secret")) >>> >>> typed_json = TypedJson.default() >>> # The secret is revealed >>> print(dumps(typed_json.to_json(person))) {"name": "John Doe", "pwd": "secret"} >>> # A custom converter can prevent revealing Password types >>> # Simple custom converters are most easily built with >>> # FunctionBasedFromSimpleJsonConverter or FunctionBasedToSimpleJsonConverter >>> password_to_str = FunctionBasedToSimpleJsonConverter(lambda pwd: "***", Password) >>> # Since a Password is also a str the new converter needs to take precedence over >>> # the existing converter for str, that is why it is prepended. >>> typed_json = typed_json.prepend([], [password_to_str]) >>> print(dumps(typed_json.to_json(person))) {"name": "John Doe", "pwd": "***"}
- to_json(o: Any) None | int | float | str | bool | Sequence[None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]] | Mapping[str, None | int | float | str | bool | Sequence[Json] | Mapping[str, Json]][source]
Convert the given object to a JSON-representation.
The JSON-representation can afterward be converted to a string containing JSON by using
json.dumps().- Parameters:
o – The object to be converted.
- Returns:
The JSON-representation.
- Raises:
ValueError – if the object cannot be converted to a JSON-representation as no suitable converter exists for the object’s type.