-
Notifications
You must be signed in to change notification settings - Fork 1.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Some optimizations for JSON #3498
Open
toppk
wants to merge
5
commits into
ethereum:main
Choose a base branch
from
toppk:json
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
@@ -1,11 +1,15 @@ | ||||||
# String encodings and numeric representations | ||||||
from collections.abc import ( | ||||||
Mapping, | ||||||
) | ||||||
import json | ||||||
import re | ||||||
from typing import ( | ||||||
Any, | ||||||
Callable, | ||||||
Dict, | ||||||
Iterable, | ||||||
List, | ||||||
Optional, | ||||||
Sequence, | ||||||
Type, | ||||||
|
@@ -191,41 +195,59 @@ class FriendlyJsonSerde: | |||||
helpful information in the raised error messages. | ||||||
""" | ||||||
|
||||||
def _json_mapping_errors(self, mapping: Dict[Any, Any]) -> Iterable[str]: | ||||||
@classmethod | ||||||
def _json_mapping_errors( | ||||||
self, | ||||||
mapping: Dict[Any, Any], | ||||||
encoder_cls: Optional[Type[json.JSONEncoder]] = None, | ||||||
) -> Iterable[str]: | ||||||
for key, val in mapping.items(): | ||||||
try: | ||||||
self._friendly_json_encode(val) | ||||||
self._friendly_json_encode(val, encoder_cls=encoder_cls) | ||||||
except TypeError as exc: | ||||||
yield f"{key!r}: because ({exc})" | ||||||
|
||||||
def _json_list_errors(self, iterable: Iterable[Any]) -> Iterable[str]: | ||||||
@classmethod | ||||||
def _json_list_errors( | ||||||
self, | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
iterable: Iterable[Any], | ||||||
encoder_cls: Optional[Type[json.JSONEncoder]] = None, | ||||||
) -> Iterable[str]: | ||||||
for index, element in enumerate(iterable): | ||||||
try: | ||||||
self._friendly_json_encode(element) | ||||||
self._friendly_json_encode(element, encoder_cls=encoder_cls) | ||||||
except TypeError as exc: | ||||||
yield f"{index}: because ({exc})" | ||||||
|
||||||
@classmethod | ||||||
def _friendly_json_encode( | ||||||
self, obj: Dict[Any, Any], cls: Optional[Type[json.JSONEncoder]] = None | ||||||
cls, | ||||||
obj: Union[Dict[Any, Any], List[Dict[Any, Any]]], | ||||||
encoder_cls: Optional[Type[json.JSONEncoder]] = None, | ||||||
) -> str: | ||||||
try: | ||||||
encoded = json.dumps(obj, cls=cls) | ||||||
encoded = json.dumps(obj, cls=encoder_cls, separators=(",", ":")) | ||||||
return encoded | ||||||
except TypeError as full_exception: | ||||||
if hasattr(obj, "items"): | ||||||
item_errors = "; ".join(self._json_mapping_errors(obj)) | ||||||
if isinstance(obj, Mapping): | ||||||
item_errors = "; ".join( | ||||||
cls._json_mapping_errors(obj, encoder_cls=encoder_cls) | ||||||
) | ||||||
raise Web3TypeError( | ||||||
f"dict had unencodable value at keys: {{{item_errors}}}" | ||||||
) | ||||||
elif is_list_like(obj): | ||||||
element_errors = "; ".join(self._json_list_errors(obj)) | ||||||
element_errors = "; ".join( | ||||||
cls._json_list_errors(obj, encoder_cls=encoder_cls) | ||||||
) | ||||||
raise Web3TypeError( | ||||||
f"list had unencodable value at index: [{element_errors}]" | ||||||
) | ||||||
else: | ||||||
raise full_exception | ||||||
|
||||||
def json_decode(self, json_str: str) -> Dict[Any, Any]: | ||||||
@classmethod | ||||||
def json_decode(cls, json_str: str) -> Dict[Any, Any]: | ||||||
try: | ||||||
decoded = json.loads(json_str) | ||||||
return decoded | ||||||
|
@@ -235,11 +257,14 @@ def json_decode(self, json_str: str) -> Dict[Any, Any]: | |||||
# so we have to re-raise the same type. | ||||||
raise json.decoder.JSONDecodeError(err_msg, exc.doc, exc.pos) | ||||||
|
||||||
@classmethod | ||||||
def json_encode( | ||||||
self, obj: Dict[Any, Any], cls: Optional[Type[json.JSONEncoder]] = None | ||||||
cls, | ||||||
obj: Union[Dict[Any, Any], List[Dict[Any, Any]]], | ||||||
encoder_cls: Optional[Type[json.JSONEncoder]] = None, | ||||||
) -> str: | ||||||
try: | ||||||
return self._friendly_json_encode(obj, cls=cls) | ||||||
return cls._friendly_json_encode(obj, encoder_cls=encoder_cls) | ||||||
except TypeError as exc: | ||||||
raise Web3TypeError(f"Could not encode to JSON: {exc}") | ||||||
|
||||||
|
@@ -306,4 +331,4 @@ def to_json(obj: Dict[Any, Any]) -> str: | |||||
""" | ||||||
Convert a complex object (like a transaction object) to a JSON string | ||||||
""" | ||||||
return FriendlyJsonSerde().json_encode(obj, cls=Web3JsonEncoder) | ||||||
return FriendlyJsonSerde.json_encode(obj, encoder_cls=Web3JsonEncoder) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.