PyQt5 Json解析、創建
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
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對象格式分為兩種??s進型和緊湊型。
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小時內刪除侵權內容。
版權聲明:本文內容由網絡用戶投稿,版權歸原作者所有,本站不擁有其著作權,亦不承擔相應法律責任。如果您發現本站中有涉嫌抄襲或描述失實的內容,請聯系我們jiasou666@gmail.com 處理,核實后本網站將在24小時內刪除侵權內容。