How to use the jsons._main_impl.load function in jsons

To help you get started, we’ve selected a few jsons examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ramonhagenaars / jsons / jsons / deserializers.py View on Github external
attr_getters=None,
                          **kwargs):
    # Loop through the signature of cls: the type we try to deserialize to. For
    # every required parameter, we try to get the corresponding value from
    # json_obj.
    attr_getters = dict(**(attr_getters or {}))
    constructor_args_in_obj = dict()
    signatures = ((sig_key, sig) for sig_key, sig in
                  signature_parameters.items() if sig_key != 'self')
    for sig_key, sig in signatures:
        if obj and sig_key in obj:
            # This argument is in obj.
            arg_cls = None
            if sig.annotation != inspect.Parameter.empty:
                arg_cls = sig.annotation
            value = _main_impl.load(obj[sig_key], arg_cls, **kwargs)
            constructor_args_in_obj[sig_key] = value
        elif sig_key in attr_getters:
            # There exists an attr_getter for this argument.
            attr_getter = attr_getters.pop(sig_key)
            constructor_args_in_obj[sig_key] = attr_getter()
        elif sig.default != inspect.Parameter.empty:
            # There is a default value for this argument.
            constructor_args_in_obj[sig_key] = sig.default
        elif sig.kind not in (inspect.Parameter.VAR_POSITIONAL,
                              inspect.Parameter.VAR_KEYWORD):
            # This argument is no *args or **kwargs and has no value.
            raise UnfulfilledArgumentError(
                'No value found for "{}"'.format(sig_key),
                sig_key, obj, cls)

    return constructor_args_in_obj, attr_getters
github ramonhagenaars / jsons / jsons / deserializers.py View on Github external
cls: type = None,
                               **kwargs) -> object:
    """
    Deserialize a (JSON) list into a tuple by deserializing all items of that
    list.
    :param obj: the tuple that needs deserializing.
    :param cls: the type optionally with a generic (e.g. Tuple[str, int]).
    :param kwargs: any keyword arguments.
    :return: a deserialized tuple instance.
    """
    if hasattr(cls, '_fields'):
        return default_namedtuple_deserializer(obj, cls, **kwargs)
    tuple_types = getattr(cls, '__tuple_params__', cls.__args__)
    if len(tuple_types) > 1 and tuple_types[1] is ...:
        tuple_types = [tuple_types[0]] * len(obj)
    list_ = [_main_impl.load(value, tuple_types[i], **kwargs)
             for i, value in enumerate(obj)]
    return tuple(list_)
github ramonhagenaars / jsons / jsons / deserializers.py View on Github external
def default_list_deserializer(obj: list, cls: type = None, **kwargs) -> list:
    """
    Deserialize a list by deserializing all items of that list.
    :param obj: the list that needs deserializing.
    :param cls: the type optionally with a generic (e.g. List[str]).
    :param kwargs: any keyword arguments.
    :return: a deserialized list instance.
    """
    cls_ = None
    if cls and hasattr(cls, '__args__'):
        cls_ = cls.__args__[0]
    return [_main_impl.load(x, cls_, **kwargs) for x in obj]
github ramonhagenaars / jsons / jsons / deserializers.py View on Github external
:param cls: the NamedTuple.
    :param kwargs: any keyword arguments.
    :return: a deserialized named tuple (i.e. an instance of a class).
    """
    args = []
    for index, field_name in enumerate(cls._fields):
        if index < len(obj):
            field = obj[index]
        else:
            field = cls._field_defaults.get(field_name, None)
        if not field:
            msg = ('No value present in {} for argument "{}"'
                   .format(obj, field_name))
            raise UnfulfilledArgumentError(msg, field_name, obj, cls)
        cls_ = cls._field_types.get(field_name, None)
        loaded_field = _main_impl.load(field, cls_, **kwargs)
        args.append(loaded_field)
    inst = cls(*args)
    return inst
github ramonhagenaars / jsons / jsons / deserializers.py View on Github external
def default_union_deserializer(obj: object, cls: Union, **kwargs) -> object:
    """
    Deserialize an object to any matching type of the given union. The first
    successful deserialization is returned.
    :param obj: The object that needs deserializing.
    :param cls: The Union type with a generic (e.g. Union[str, int]).
    :param kwargs: Any keyword arguments that are passed through the
    deserialization process.
    :return: An object of the first type of the Union that could be
    deserialized successfully.
    """
    for sub_type in cls.__args__:
        try:
            return _main_impl.load(obj, sub_type, **kwargs)
        except JsonsError:
            pass  # Try the next one.
    else:
        args_msg = ', '.join([get_class_name(cls_) for cls_ in cls.__args__])
        err_msg = ('Could not match the object of type "{}" to any type of '
                   'the Union: {}'.format(str(cls), args_msg))
        raise DeserializationError(err_msg, obj, cls)
github ramonhagenaars / jsons / jsons / deserializers.py View on Github external
def _set_remaining_attrs(instance,
                         remaining_attrs,
                         attr_getters=None,
                         **kwargs):
    # Set any remaining attributes on the newly created instance.
    attr_getters = attr_getters or {}
    for attr_name in remaining_attrs:
        loaded_attr = _main_impl.load(remaining_attrs[attr_name],
                                      type(remaining_attrs[attr_name]),
                                      **kwargs)
        try:
            setattr(instance, attr_name, loaded_attr)
        except AttributeError:
            pass  # This is raised when a @property does not have a setter.
    for attr_name, getter in attr_getters.items():
        setattr(instance, attr_name, getter())
github ramonhagenaars / jsons / jsons / deserializers.py View on Github external
def default_string_deserializer(obj: str,
                                cls: Optional[type] = None,
                                **kwargs) -> object:
    """
    Deserialize a string. If the given ``obj`` can be parsed to a date, a
    ``datetime`` instance is returned.
    :param obj: the string that is to be deserialized.
    :param cls: not used.
    :param kwargs: any keyword arguments.
    :return: the deserialized obj.
    """
    try:
        # Use load instead of default_datetime_deserializer to allow the
        # datetime deserializer to be overridden.
        return _main_impl.load(obj, datetime, **kwargs)
    except:
        return obj
github ramonhagenaars / jsons / jsons / deserializers.py View on Github external
**kwargs) -> dict:
    """
    Deserialize a dict by deserializing all instances of that dict.
    :param obj: the dict that needs deserializing.
    :param key_transformer: a function that transforms the keys to a different
    style (e.g. PascalCase).
    :param cls: not used.
    :param kwargs: any keyword arguments.
    :return: a deserialized dict instance.
    """
    key_transformer = key_transformer or (lambda key: key)
    kwargs_ = {**{'key_transformer': key_transformer}, **kwargs}
    if hasattr(cls, '__args__') and len(cls.__args__) > 1:
        sub_cls = cls.__args__[1]
        kwargs_['cls'] = sub_cls
    return {key_transformer(key): _main_impl.load(obj[key], **kwargs_)
            for key in obj}