Skip to content

json

xsdata.formats.dataclass.serializers.json

DictFactory

Dictionary factory types.

Source code in xsdata/formats/dataclass/serializers/json.py
27
28
29
30
class DictFactory:
    """Dictionary factory types."""

    FILTER_NONE = filter_none

JsonSerializer dataclass

Bases: AbstractSerializer

Json serializer for data classes.

Parameters:

Name Type Description Default
config SerializerConfig

The serializer config instance

field(default_factory=SerializerConfig)
context XmlContext

The models context instance

field(default_factory=XmlContext)
dict_factory Callable

Dictionary factory

field(default=dict)
dump_factory Callable

Json dump factory e.g. json.dump

field(default=dump)
Source code in xsdata/formats/dataclass/serializers/json.py
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
@dataclass
class JsonSerializer(AbstractSerializer):
    """Json serializer for data classes.

    Args:
        config: The serializer config instance
        context: The models context instance
        dict_factory: Dictionary factory
        dump_factory: Json dump factory e.g. json.dump
    """

    config: SerializerConfig = field(default_factory=SerializerConfig)
    context: XmlContext = field(default_factory=XmlContext)
    dict_factory: Callable = field(default=dict)
    dump_factory: Callable = field(default=json.dump)

    def render(self, obj: Any) -> str:
        """Serialize the input model instance to json string.

        Args:
            obj: The input model instance

        Returns:
            The serialized json string output.
        """
        output = StringIO()
        self.write(output, obj)
        return output.getvalue()

    def write(self, out: TextIO, obj: Any):
        """Serialize the given object to the output text stream.

        Args:
            out: The output text stream
            obj: The input model instance to serialize
        """
        indent: Optional[Union[int, str]] = None
        if self.config.pretty_print:
            indent = self.config.pretty_print_indent or 2

        self.dump_factory(self.convert(obj), out, indent=indent)

    def convert(self, value: Any, var: Optional[XmlVar] = None) -> Any:
        """Convert a value to json serializable object.

        Args:
            value: The input value
            var: The xml var instance

        Returns:
            The converted json serializable value.
        """
        if var is None or self.context.class_type.is_model(value):
            if collections.is_array(value):
                return list(map(self.convert, value))

            return self.dict_factory(self.next_value(value))

        if collections.is_array(value):
            return type(value)(self.convert(val, var) for val in value)

        if isinstance(value, (dict, int, float, str, bool)):
            return value

        if isinstance(value, Enum):
            return self.convert(value.value, var)

        return converter.serialize(value, format=var.format)

    def next_value(self, obj: Any) -> Iterator[Tuple[str, Any]]:
        """Fetch the next value of a model instance to convert.

        Args:
            obj: The input model instance

        Yields:
            An iterator of field name and value tuples.
        """
        ignore_optionals = self.config.ignore_default_attributes
        meta = self.context.build(obj.__class__, globalns=self.config.globalns)

        for var in meta.get_all_vars():
            value = getattr(obj, var.name)
            if (
                not var.is_attribute
                or not ignore_optionals
                or not var.is_optional(value)
            ):
                yield var.local_name, self.convert(value, var)

render(obj)

Serialize the input model instance to json string.

Parameters:

Name Type Description Default
obj Any

The input model instance

required

Returns:

Type Description
str

The serialized json string output.

Source code in xsdata/formats/dataclass/serializers/json.py
49
50
51
52
53
54
55
56
57
58
59
60
def render(self, obj: Any) -> str:
    """Serialize the input model instance to json string.

    Args:
        obj: The input model instance

    Returns:
        The serialized json string output.
    """
    output = StringIO()
    self.write(output, obj)
    return output.getvalue()

write(out, obj)

Serialize the given object to the output text stream.

Parameters:

Name Type Description Default
out TextIO

The output text stream

required
obj Any

The input model instance to serialize

required
Source code in xsdata/formats/dataclass/serializers/json.py
62
63
64
65
66
67
68
69
70
71
72
73
def write(self, out: TextIO, obj: Any):
    """Serialize the given object to the output text stream.

    Args:
        out: The output text stream
        obj: The input model instance to serialize
    """
    indent: Optional[Union[int, str]] = None
    if self.config.pretty_print:
        indent = self.config.pretty_print_indent or 2

    self.dump_factory(self.convert(obj), out, indent=indent)

convert(value, var=None)

Convert a value to json serializable object.

Parameters:

Name Type Description Default
value Any

The input value

required
var Optional[XmlVar]

The xml var instance

None

Returns:

Type Description
Any

The converted json serializable value.

Source code in xsdata/formats/dataclass/serializers/json.py
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
def convert(self, value: Any, var: Optional[XmlVar] = None) -> Any:
    """Convert a value to json serializable object.

    Args:
        value: The input value
        var: The xml var instance

    Returns:
        The converted json serializable value.
    """
    if var is None or self.context.class_type.is_model(value):
        if collections.is_array(value):
            return list(map(self.convert, value))

        return self.dict_factory(self.next_value(value))

    if collections.is_array(value):
        return type(value)(self.convert(val, var) for val in value)

    if isinstance(value, (dict, int, float, str, bool)):
        return value

    if isinstance(value, Enum):
        return self.convert(value.value, var)

    return converter.serialize(value, format=var.format)

next_value(obj)

Fetch the next value of a model instance to convert.

Parameters:

Name Type Description Default
obj Any

The input model instance

required

Yields:

Type Description
str

An iterator of field name and value tuples.

Source code in xsdata/formats/dataclass/serializers/json.py
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
def next_value(self, obj: Any) -> Iterator[Tuple[str, Any]]:
    """Fetch the next value of a model instance to convert.

    Args:
        obj: The input model instance

    Yields:
        An iterator of field name and value tuples.
    """
    ignore_optionals = self.config.ignore_default_attributes
    meta = self.context.build(obj.__class__, globalns=self.config.globalns)

    for var in meta.get_all_vars():
        value = getattr(obj, var.name)
        if (
            not var.is_attribute
            or not ignore_optionals
            or not var.is_optional(value)
        ):
            yield var.local_name, self.convert(value, var)

filter_none(x)

Convert a key-value pairs to dict, ignoring None values.

Parameters:

Name Type Description Default
x Tuple

Key-value pairs

required

Returns:

Type Description
Dict

The filtered dictionary.

Source code in xsdata/formats/dataclass/serializers/json.py
15
16
17
18
19
20
21
22
23
24
def filter_none(x: Tuple) -> Dict:
    """Convert a key-value pairs to dict, ignoring None values.

    Args:
        x: Key-value pairs

    Returns:
        The filtered dictionary.
    """
    return {k: v for k, v in x if v is not None}