Skip to content

JsonDocument

Qt Base Class: QJsonDocument

Signature: QJsonDocument(self) -> None QJsonDocument(self, array: PySide6.QtCore.QJsonArray) -> None QJsonDocument(self, object: Dict[str, PySide6.QtCore.QJsonValue]) -> None QJsonDocument(self, other: PySide6.QtCore.QJsonDocument) -> None

Base classes

Name Children Inherits
QJsonDocument
PySide6.QtCore
QJsonDocument(self) -> None

⋔ Inheritance diagram

graph TD
  1473299915552["core.JsonDocument"]
  1473243592928["QtCore.QJsonDocument"]
  1473291690208["Shiboken.Object"]
  140713234304496["builtins.object"]
  1473243592928 --> 1473299915552
  1473291690208 --> 1473243592928
  140713234304496 --> 1473291690208

🛈 DocStrings

Bases: QJsonDocument

Way to read and write JSON documents.

Source code in prettyqt\core\jsondocument.py
class JsonDocument(core.QJsonDocument):
    """Way to read and write JSON documents."""

    def __str__(self):
        return str(self.toVariant())

    def __format__(self, fmt):
        if fmt in JSON_FORMAT:
            return self.to_string(fmt == "indented")
        return super().__format__(fmt)

    def __repr__(self):
        return get_repr(self, self.toVariant())

    def __getitem__(self, index: int | str):
        val = self.array() if self.isArray() else self.object()
        return core.JsonValue(val[index])  # type: ignore

    def __setitem__(self, index: int | str, value):
        if self.isArray():
            if not isinstance(index, int):
                raise TypeError
            array = self.array()
            array[index] = value
            self.setArray(array)
        elif self.isObject():
            if not isinstance(index, str):
                raise TypeError
            obj = self.object()
            obj[index] = value
            self.setObject(obj)

    def to_string(self, indented: bool = False) -> str:
        flag = self.JsonFormat.Indented if indented else self.JsonFormat.Compact
        return self.toJson(flag).data().decode()

    @classmethod
    def from_variant(cls, obj) -> Self:
        doc = cls.fromVariant(obj)
        new = cls()
        if doc.isArray():
            new.setArray(doc.array())
        else:
            new.setObject(doc.object())
        return new