Exemplo n.º 1
0
    def serialize(self, metadata_obj: Metadata) -> bytes:
        """Serialize Metadata object into utf-8 encoded JSON bytes."""

        try:
            indent = None if self.compact else 1
            separators = (",", ":") if self.compact else (",", ": ")
            json_bytes = json.dumps(
                metadata_obj.to_dict(),
                indent=indent,
                separators=separators,
                sort_keys=True,
            ).encode("utf-8")

            if self.validate:
                try:
                    new_md_obj = JSONDeserializer().deserialize(json_bytes)
                    if metadata_obj != new_md_obj:
                        raise ValueError(
                            "Metadata changes if you serialize and deserialize."
                        )
                except Exception as e:
                    raise ValueError("Metadata cannot be validated!") from e

        except Exception as e:
            raise SerializationError("Failed to serialize JSON") from e

        return json_bytes
Exemplo n.º 2
0
Arquivo: json.py Projeto: sechkova/tuf
    def serialize(self, metadata_obj: Metadata) -> bytes:
        """Serialize Metadata object into utf-8 encoded JSON bytes."""
        try:
            indent = None if self.compact else 1
            separators = (",", ":") if self.compact else (",", ": ")
            json_bytes = json.dumps(
                metadata_obj.to_dict(),
                indent=indent,
                separators=separators,
                sort_keys=True,
            ).encode("utf-8")

        except Exception as e:  # pylint: disable=broad-except
            raise SerializationError from e

        return json_bytes