PyQt5 Json解析、创建

网友投稿 1177 2022-05-30

PyQt5 Json解析、创建

简介

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

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

分别有:

PyQt5 支持的json接口 如下:

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

支持的json 接口如下:

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

#QtCore.pyi class QMetaType(sip.simplewrapper): QJsonValue = ... # type: 'QMetaType.Type' QJsonObject = ... # type: 'QMetaType.Type' QJsonArray = ... # type: 'QMetaType.Type' QJsonDocument = ... # type: 'QMetaType.Type'

1

2

3

4

5

6

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

Json解析

思路

同C++一样,解析Json。

1.获取Json数据块,读取文件是QFile打开文件,读取文件数据 jsondata

2.通过QJsonDocument 将json数据序列化转化为 QJsonObject对象

3.对QJsonObject进行处理

源码

1.打开文件

file = QFile("config.json") file.open(QFile.ReadOnly | QFile.Text) if file.isOpen() == 1: data = file.readAll()

1

2

3

4

2.进行序列化

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

1

2

3

4

3.解析JSON

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") 判断该属性是否存在

1

2

3

4

5

6

7

8

9

10

11

12

4.处理结果

config.json #文件内容如下

1

{ "name":"wq", "attri":[ {"time":"11:00"}, {"time":"12:00"} ], "type":"person" }

1

2

3

4

5

6

7

8

处理结果:

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

1

2

3

4

5

5.contains 测试

代码修改如下:

j = jsonparse(data) if j.__contains__("names") == 1: name = j["name"].toString() print(name) jarrt = j["attri"].toArray()

1

2

3

4

5

输出结果如下:

b'{\n "name":"wq",\n "attri":[\n {"time":"11:00"},\n {"time":"12:00"}\n ],\n "type":"person"\n}' person 11:00 12:00

PyQt5 Json解析、创建

1

2

3

4

将代码修改如下:

if j.__contains__("name") == 1: name = j["name"].toString() print(name) jarrt = j["attri"].toArray()

1

2

3

4

执行结果如下:

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

1

2

3

4

5

6

JSON 创建

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

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

源码

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)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

执行结果

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}'

1

JsonFormat

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

QJsonDocument::Indented #缩进型 QJsonDocument::Compact #紧凑型

1

2

其中 toJson默认缩进型。即:

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

1

2

执行结果

b'{\n "items": [\n {\n "type": "win",\n "value": 0\n },\n {\n "type": "win",\n "value": 1\n },\n {\n "type": "win",\n "value": 2\n },\n {\n "type": "win",\n "value": 3\n },\n {\n "type": "win",\n "value": 4\n }\n ],\n "name": "wq",\n "value": 5\n}\n'

1

或者

outputjson = QJsonDocument(json).toJson(QJsonDocument.Indented) print(outputjson)

1

2

执行结果为:

b'{\n "items": [\n {\n "type": "win",\n "value": 0\n },\n {\n "type": "win",\n "value": 1\n },\n {\n "type": "win",\n "value": 2\n },\n {\n "type": "win",\n "value": 3\n },\n {\n "type": "win",\n "value": 4\n }\n ],\n "name": "wq",\n "value": 5\n}\n'

1

紧凑型

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

1

2

执行结果:

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}'

1

QJsonDocument接口如下

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': ...

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

QJsonValue接口如下

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': ...

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

QJsonParseError接口如下

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: ...

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

import

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

1

2

3

4

5

6

7

8

JSON

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:65_Java_常用类3_enum_注解Annotation
下一篇:ABAP Netweaver体内的那些寄生式编程语言
相关文章