PyQt5 Json解析、创建

2023-03-10 13:18:59 浏览数 (1)

PyQt5 Json解析、创建

简介

最近做了几个小程序,用到了QJson 相关的一些代码,想着在python下测试一下,折腾一番还是整理出来了。

从C 接口知道 ,QJson 相关接口在QtCore下边。

分别有:

Class name

Description

QJsonDocument

Way to read and write JSON documents

QJsonParseError

Used to report errors during JSON parsing

QJsonObject

Encapsulates a JSON object

QJsonValue

Encapsulates a value in JSON

QJsonArray

Encapsulates a JSON array

PyQt5 支持的json接口 如下:

链接:https://www.riverbankcomputing.com/static/Docs/PyQt5/api/qtcore/qtcore-module.html

支持的json 接口如下:

Class name

Description

QJsonDocument

Way to read and write JSON documents

QJsonParseError

Used to report errors during JSON parsing

QJsonValue

Encapsulates a value in JSON

从官方文档来看没有对外暴露的QJsonObject,QJsonValue 接口。但是注意:在QMetaType中,可以看到对外提供的接口包含有QJsonObject 这个方法。

代码语言:javascript复制
   #QtCore.pyi
class QMetaType(sip.simplewrapper):
    QJsonValue = ... # type: 'QMetaType.Type'
    QJsonObject = ... # type: 'QMetaType.Type'
    QJsonArray = ... # type: 'QMetaType.Type'
    QJsonDocument = ... # type: 'QMetaType.Type'

从QMetaType 类来看,PyQt5 支持QJsonObject,QJsonArray这两个属性。下面就是怎么提取到这两个属性了。

Json解析

思路

同C 一样,解析Json。

1.获取Json数据块,读取文件是QFile打开文件,读取文件数据 jsondata 2.通过QJsonDocument 将json数据序列化转化为 QJsonObject对象 3.对QJsonObject进行处理

源码

1.打开文件

代码语言:javascript复制
file = QFile("config.json")
file.open(QFile.ReadOnly | QFile.Text)
if file.isOpen() == 1:
    data = file.readAll()

2.进行序列化

代码语言:javascript复制
def jsonparse(data):
    error = QJsonParseError()
    json = QJsonDocument.fromJson(data,error)  # 通过fromjson 获取 QJsonDocument对象
    return json.object() #将Json数据转为 QJsonObject

3.解析JSON

代码语言:javascript复制
if file.isOpen() == 1:
    data = file.readAll()
    print(data)
    j = jsonparse(data)
    name = j["name"].toString()
    jarrt = j["attri"].toArray()
    jtype = j["type"].toString()
    print(name,jtype)
    for i in jarrt: #数组解析如下
        items = i.toObject()
        print(items["time"].toString())
#json.contains("name") 判断该属性是否存在

4.处理结果

代码语言:javascript复制
config.json #文件内容如下
代码语言:javascript复制
{
    "name":"wq",
    "attri":[
        {"time":"11:00"},
        {"time":"12:00"}
    ],
    "type":"person"
}

处理结果:

代码语言:javascript复制
python3 json.py 
b'{n    "name":"wq",n    "attri":[n        {"time":"11:00"},n        {"time":"12:00"}n    ],n    "type":"person"n}'
wq person
11:00
12:00

5.contains 测试

代码修改如下:

代码语言:javascript复制
    j = jsonparse(data)
    if j.__contains__("names") == 1:
        name = j["name"].toString()
        print(name)
    jarrt = j["attri"].toArray()

输出结果如下:

代码语言:javascript复制
b'{n    "name":"wq",n    "attri":[n        {"time":"11:00"},n        {"time":"12:00"}n    ],n    "type":"person"n}'
person
11:00
12:00

将代码修改如下:

代码语言:javascript复制
    if j.__contains__("name") == 1:
        name = j["name"].toString()
        print(name)
    jarrt = j["attri"].toArray()

执行结果如下:

代码语言:javascript复制
python3 json.py 
b'{n    "name":"wq",n    "attri":[n        {"time":"11:00"},n        {"time":"12:00"}n    ],n    "type":"person"n}'
wq
person
11:00
12:00

JSON 创建

回答上诉的一些疑点,没有QJsonObjec对外接口怎么创建Json文件。

通过 QJsonDocument 创建 QJsonObect对象 ,通过 **.object()**获取QJsonObject对象。

源码

代码语言:javascript复制
def jsonCreate():
    data = QByteArray()
    json = QJsonDocument.fromJson(data).object() #创建空的QJsonObject对象
    json["name"]="wq"
    json["value"]=5
    jsonarry = QJsonDocument.fromJson(data).array() # 创建空的QJsonArray对象。
    for i in range(0,5):
        jsontems = QJsonDocument.fromJson(data).object()
        jsontems["type"]="win"
        jsontems["value"]=i
        jsonarry.append(jsontems)
    json["items"]=jsonarry
    return json

json = jsonCreate()
outputjson = QJsonDocument(json).toJson(QJsonDocument.Compact)
print(outputjson)

执行结果

代码语言:javascript复制
b'{"items":[{"type":"win","value":0},{"type":"win","value":1},{"type":"win","value":2},{"type":"win","value":3},{"type":"win","value":4}],"name":"wq","value":5}'

JsonFormat

在Qt中Json对象格式分为两种。缩进型和紧凑型。

代码语言:javascript复制
QJsonDocument::Indented #缩进型
QJsonDocument::Compact #紧凑型

其中 toJson默认缩进型。即:

代码语言:javascript复制
outputjson = QJsonDocument(json).toJson()
print(outputjson)

执行结果

代码语言:javascript复制
b'{n    "items": [n        {n            "type": "win",n            "value": 0n        },n        {n            "type": "win",n            "value": 1n        },n        {n            "type": "win",n            "value": 2n        },n        {n            "type": "win",n            "value": 3n        },n        {n            "type": "win",n            "value": 4n        }n    ],n    "name": "wq",n    "value": 5n}n'

或者

代码语言:javascript复制
outputjson = QJsonDocument(json).toJson(QJsonDocument.Indented)
print(outputjson)

执行结果为:

代码语言:javascript复制
b'{n    "items": [n        {n            "type": "win",n            "value": 0n        },n        {n            "type": "win",n            "value": 1n        },n        {n            "type": "win",n            "value": 2n        },n        {n            "type": "win",n            "value": 3n        },n        {n            "type": "win",n            "value": 4n        }n    ],n    "name": "wq",n    "value": 5n}n'

紧凑型

代码语言:javascript复制
outputjson = QJsonDocument(json).toJson(QJsonDocument.Compact)
print(outputjson)

执行结果:

代码语言:javascript复制
b'{"items":[{"type":"win","value":0},{"type":"win","value":1},{"type":"win","value":2},{"type":"win","value":3},{"type":"win","value":4}],"name":"wq","value":5}'

QJsonDocument接口如下

代码语言:javascript复制
class QJsonDocument(sip.simplewrapper):

    class JsonFormat(int): ...
    Indented = ... # type: 'QJsonDocument.JsonFormat'
    Compact = ... # type: 'QJsonDocument.JsonFormat'

    class DataValidation(int): ...
    Validate = ... # type: 'QJsonDocument.DataValidation'
    BypassValidation = ... # type: 'QJsonDocument.DataValidation'

    @typing.overload
    def __init__(self) -> None: ...
    @typing.overload
    def __init__(self, object: typing.Dict[str, typing.Union['QJsonValue', 'QJsonValue.Type', typing.Iterable['QJsonValue'], bool, int, float, None, str]]) -> None: ...
    @typing.overload
    def __init__(self, array: typing.Iterable['QJsonValue']) -> None: ...
    @typing.overload
    def __init__(self, other: 'QJsonDocument') -> None: ...

    @typing.overload
    def __getitem__(self, key: str) -> 'QJsonValue': ...
    @typing.overload
    def __getitem__(self, i: int) -> 'QJsonValue': ...
    def swap(self, other: 'QJsonDocument') -> None: ...
    def isNull(self) -> bool: ...
    def setArray(self, array: typing.Iterable['QJsonValue']) -> None: ...
    def setObject(self, object: typing.Dict[str, typing.Union['QJsonValue', 'QJsonValue.Type', typing.Iterable['QJsonValue'], bool, int, float, None, str]]) -> None: ...
    def array(self) -> typing.List['QJsonValue']: ...
    def object(self) -> typing.Dict[str, typing.Union['QJsonValue', 'QJsonValue.Type', typing.Iterable['QJsonValue'], bool, int, float, None, str]]: ...
    def isObject(self) -> bool: ...
    def isArray(self) -> bool: ...
    def isEmpty(self) -> bool: ...
    @typing.overload
    def toJson(self) -> QByteArray: ...
    @typing.overload
    def toJson(self, format: 'QJsonDocument.JsonFormat') -> QByteArray: ...
    @staticmethod
    def fromJson(json: typing.Union[QByteArray, bytes, bytearray], error: typing.Optional[QJsonParseError] = ...) -> 'QJsonDocument': ...
    def toVariant(self) -> typing.Any: ...
    @staticmethod
    def fromVariant(variant: typing.Any) -> 'QJsonDocument': ...
    def toBinaryData(self) -> QByteArray: ...
    @staticmethod
    def fromBinaryData(data: typing.Union[QByteArray, bytes, bytearray], validation: 'QJsonDocument.DataValidation' = ...) -> 'QJsonDocument': ...
    def rawData(self) -> typing.Tuple[str, int]: ...
    @staticmethod
    def fromRawData(data: str, size: int, validation: 'QJsonDocument.DataValidation' = ...) -> 'QJsonDocument': ...

QJsonValue接口如下

代码语言:javascript复制
class QJsonValue(sip.simplewrapper):

    class Type(int): ...
    Null = ... # type: 'QJsonValue.Type'
    Bool = ... # type: 'QJsonValue.Type'
    Double = ... # type: 'QJsonValue.Type'
    String = ... # type: 'QJsonValue.Type'
    Array = ... # type: 'QJsonValue.Type'
    Object = ... # type: 'QJsonValue.Type'
    Undefined = ... # type: 'QJsonValue.Type'

    @typing.overload
    def __init__(self, type: 'QJsonValue.Type' = ...) -> None: ...
    @typing.overload
    def __init__(self, other: typing.Union['QJsonValue', 'QJsonValue.Type', typing.Iterable['QJsonValue'], bool, int, float, None, str]) -> None: ...

    def __hash__(self) -> int: ...
    @typing.overload
    def __getitem__(self, key: str) -> 'QJsonValue': ...
    @typing.overload
    def __getitem__(self, i: int) -> 'QJsonValue': ...
    def swap(self, other: 'QJsonValue') -> None: ...
    @typing.overload
    def toString(self) -> str: ...
    @typing.overload
    def toString(self, defaultValue: str) -> str: ...
    @typing.overload
    def toObject(self) -> typing.Dict[str, typing.Union['QJsonValue', 'QJsonValue.Type', typing.Iterable['QJsonValue'], bool, int, float, None, str]]: ...
    @typing.overload
    def toObject(self, defaultValue: typing.Dict[str, typing.Union['QJsonValue', 'QJsonValue.Type', typing.Iterable['QJsonValue'], bool, int, float, None, str]]) -> typing.Dict[str, typing.Union['QJsonValue', 'QJsonValue.Type', typing.Iterable['QJsonValue'], bool, int, float, None, str]]: ...
    @typing.overload
    def toArray(self) -> typing.List['QJsonValue']: ...
    @typing.overload
    def toArray(self, defaultValue: typing.Iterable['QJsonValue']) -> typing.List['QJsonValue']: ...
    def toDouble(self, defaultValue: float = ...) -> float: ...
    def toInt(self, defaultValue: int = ...) -> int: ...
    def toBool(self, defaultValue: bool = ...) -> bool: ...
    def isUndefined(self) -> bool: ...
    def isObject(self) -> bool: ...
    def isArray(self) -> bool: ...
    def isString(self) -> bool: ...
    def isDouble(self) -> bool: ...
    def isBool(self) -> bool: ...
    def isNull(self) -> bool: ...
    def type(self) -> 'QJsonValue.Type': ...
    def toVariant(self) -> typing.Any: ...
    @staticmethod
    def fromVariant(variant: typing.Any) -> 'QJsonValue': ...

QJsonParseError接口如下

代码语言:javascript复制
class QJsonParseError(sip.simplewrapper):

    class ParseError(int): ...
    NoError = ... # type: 'QJsonParseError.ParseError'
    UnterminatedObject = ... # type: 'QJsonParseError.ParseError'
    MissingNameSeparator = ... # type: 'QJsonParseError.ParseError'
    UnterminatedArray = ... # type: 'QJsonParseError.ParseError'
    MissingValueSeparator = ... # type: 'QJsonParseError.ParseError'
    IllegalValue = ... # type: 'QJsonParseError.ParseError'
    TerminationByNumber = ... # type: 'QJsonParseError.ParseError'
    IllegalNumber = ... # type: 'QJsonParseError.ParseError'
    IllegalEscapeSequence = ... # type: 'QJsonParseError.ParseError'
    IllegalUTF8String = ... # type: 'QJsonParseError.ParseError'
    UnterminatedString = ... # type: 'QJsonParseError.ParseError'
    MissingObject = ... # type: 'QJsonParseError.ParseError'
    DeepNesting = ... # type: 'QJsonParseError.ParseError'
    DocumentTooLarge = ... # type: 'QJsonParseError.ParseError'
    GarbageAtEnd = ... # type: 'QJsonParseError.ParseError'

    error = ... # type: 'QJsonParseError.ParseError'
    offset = ... # type: int

    @typing.overload
    def __init__(self) -> None: ...
    @typing.overload
    def __init__(self, a0: 'QJsonParseError') -> None: ...

    def errorString(self) -> str: ...

import

代码语言:javascript复制
from PyQt5.QtCore import QMetaType
from PyQt5.QtCore import QJsonDocument
from PyQt5.QtCore import QJsonValue
from PyQt5.QtCore import QJsonParseError
from PyQt5.QtCore import QMetaObject
from PyQt5.QtCore import QByteArray
from PyQt5.QtCore import QFile
from PyQt5.QtCore import QFileDevice

0 人点赞