Skip to content

Commit

Permalink
Improve JSON parsing (#315)
Browse files Browse the repository at this point in the history
  • Loading branch information
Vaskivskyi authored Oct 30, 2023
1 parent 1b0d8f1 commit 4593368
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 2 deletions.
3 changes: 3 additions & 0 deletions asusrouter/modules/endpoint/onboarding.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ def read(content: str) -> dict[str, Any]:
)
content = '{"' + content[:-3] + "}"

# In case we have a trailing comma inside a dict
content = content.replace(",}", "}")

# Read the json content
onboarding: dict[str, Any] = read_json_content(content)

Expand Down
1 change: 0 additions & 1 deletion asusrouter/modules/homeassistant.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,6 @@ def convert_to_ha_string(data: Any) -> str:
# Check whether value is an enum or a string
# If string, return it, if enum, go recursive
if isinstance(data, Enum):
print("Enum")
return convert_to_ha_string(data.value)

# Check if we have string
Expand Down
32 changes: 31 additions & 1 deletion asusrouter/tools/readers.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,30 @@
from __future__ import annotations

import json
import logging
import re
from typing import Any, Optional

from asusrouter.const import ContentType
from asusrouter.tools.converters import clean_string

_LOGGER = logging.getLogger(__name__)


# Random symbols to avoid json errors
RANDOM_SYMBOLS: list[str] = [
"\u0000",
"\u0001",
"\u0002",
"\u0003",
"\u0004",
"\u0005",
"\u0006",
"\u0007",
"\u0008",
"\u0009",
]


def merge_dicts(data: dict[Any, Any], merge_data: dict[Any, Any]) -> dict[Any, Any]:
"""This methods merges two nested dicts into a single one
Expand Down Expand Up @@ -117,8 +135,20 @@ def read_json_content(content: Optional[str]) -> dict[str, Any]:
if not content:
return {}

# Random control characters to avoid json errors
for symbol in RANDOM_SYMBOLS:
content = content.replace(symbol, "")

# Return the json content
return json.loads(content.encode().decode("utf-8-sig"))
try:
return json.loads(content.encode().decode("utf-8-sig"))
except json.JSONDecodeError as ex:
_LOGGER.error(
"Unable to decode json content with exception `%s`. Please, copy this end fill in a bug report: %s",
ex,
content,
)
return {}


def readable_mac(raw: str) -> bool:
Expand Down

0 comments on commit 4593368

Please sign in to comment.