2 回答

TA貢獻(xiàn)1864條經(jīng)驗(yàn) 獲得超6個(gè)贊
為這個(gè)任務(wù)編寫解析器的想法在智力上真的很有趣,但我強(qiáng)烈警告你不要遵循這種方法。
根本問(wèn)題是,當(dāng)網(wǎng)絡(luò)請(qǐng)求失敗時(shí),您將進(jìn)入未定義行為的領(lǐng)域。你絕對(duì)不能保證你的結(jié)果輸出會(huì)是什么,所以你可能不應(yīng)該嘗試修改一個(gè)。
這兩種可能性要么是您的輸入不完整但部分可理解,要么是完全不可理解。增加的復(fù)雜性與失敗的網(wǎng)絡(luò)請(qǐng)求的未定義性質(zhì)相結(jié)合意味著您可能不應(yīng)該嘗試定義它。
以TCP/IP 協(xié)議如何處理類似問(wèn)題為例。對(duì)于網(wǎng)絡(luò),經(jīng)常會(huì)出現(xiàn)數(shù)據(jù)包丟失,這意味著部分?jǐn)?shù)據(jù)無(wú)法完全傳輸。引用維基百科的話說(shuō),TCP“檢測(cè)數(shù)據(jù)包丟失并執(zhí)行重傳以確保可靠的消息傳遞”。
我強(qiáng)烈建議采用類似的方法。要么重新獲取數(shù)據(jù),要么簡(jiǎn)單地將錯(cuò)誤視為福音,并對(duì)錯(cuò)誤狀態(tài)進(jìn)行處理。

TA貢獻(xiàn)1860條經(jīng)驗(yàn) 獲得超9個(gè)贊
這是我這樣做的方式,構(gòu)建一堆}和]字符來(lái)嘗試“完成”。它有點(diǎn)冗長(zhǎng),可以清理,但它適用于我嘗試過(guò)的一些字符串輸入:
s='''{
"response": 200,
"message": null,
"params": [],
"body": {
"timestamp": 1546033192,
"_d": [
{"id": "FMfcgxwBTsWRDsWDqgqRtZlLMdpCpTDz"},
{"id": "FMfcgxwBTkFSKqRrcKzMFvLCjDSSbrJH"},
{"id": "Fmfgo9'''
>>> f.complete_json_structure(s)
{'response': 200, 'message': None, 'params': [], 'body': {'timestamp': 1546033192, '_d': [{'id': 'FMfcgxwBTsWRDsWDqgqRtZlLMdpCpTDz'}, {'id': 'FMfcgxwBTkFSKqRrcKzMFvLCjDSSbrJH'}]}}
這是代碼:
# Build the 'unfinished character' stack
unfinished = []
for char in file_data:
if char in ['{', '[']:
unfinished.append(char)
elif char in ['}', ']']:
inverse_char = '{' if char == '}' else '['
# Remove the last one
unfinished.reverse()
unfinished.remove(inverse_char)
unfinished.reverse()
# Build the 'closing occurrence string'
unfinished.reverse()
unfinished = ['}' if (char == '{') else ']' for char in unfinished]
unfinished_str = ''.join(unfinished)
# Do a while loop to try and parse the json
data = None
while True:
if not json_string:
raise FileParserError("Could not parse the JSON file or infer its format.")
if json_string[-1] in ('}', ']'):
try:
data = json.loads(json_string + unfinished_str)
except json.decoder.JSONDecodeError:
# do it a second time as a sort of hack to fix the "trailing comma issue" (or could do a remove last comma, but that gets tricky)
try:
data = json.loads(json_string + unfinished_str[1:])
except json.decoder.JSONDecodeError:
pass
if data is not None:
break
if json_string[-1] == unfinished_str[0]:
unfinished_str = unfinished_str[1:]
json_string = json_string[:-1].strip().rstrip(',')
return data
添加回答
舉報(bào)