Skip to content

Commit e695d72

Browse files
committed
try_parse_json_object
1 parent d39cc8b commit e695d72

2 files changed

Lines changed: 21 additions & 0 deletions

File tree

src/jmcomic/jm_client_interface.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,13 @@ def json(self) -> Dict:
116116
def is_success(self) -> bool:
117117
return super().is_success and self.json()['code'] == 200
118118

119+
def json(self) -> Dict:
120+
try:
121+
text = self.resp.text
122+
return JmcomicText.try_parse_json_object(text)
123+
except Exception as e:
124+
ExceptionTool.raises_resp(f'json解析失败: {e}', self, JsonResolveFailException)
125+
119126
@property
120127
@field_cache()
121128
def decoded_data(self) -> str:

src/jmcomic/jm_toolkit.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,8 @@ class JmcomicText:
6161

6262
# 提取接口返回值信息
6363
pattern_ajax_favorite_msg = compile(r'</button>(.*?)</div>')
64+
# 提取api接口返回值里的json,防止返回值里有无关日志导致json解析报错
65+
pattern_api_response_json_object = re.compile(r'\{.*?}')
6466

6567
@classmethod
6668
def parse_to_jm_domain(cls, text: str):
@@ -344,6 +346,18 @@ def try_mkdir(cls, save_dir: str):
344346
raise e
345347
return save_dir
346348

349+
# noinspection PyTypeChecker
350+
@classmethod
351+
def try_parse_json_object(cls, text: str) -> dict:
352+
import json
353+
text = text.strip()
354+
if text.startswith('{') and text.endswith('}'):
355+
# fast case
356+
return json.loads(text)
357+
358+
for match in cls.pattern_api_response_json_object.finditer(text):
359+
return json.loads(match.group(0))
360+
347361

348362
# 支持dsl: #{???} -> os.getenv(???)
349363
JmcomicText.dsl_replacer.add_dsl_and_replacer(r'\$\{(.*?)\}', JmcomicText.match_os_env)

0 commit comments

Comments
 (0)