Skip to content

Commit 48840d1

Browse files
authored
Fix: ValidatedEmail is not JSON serializable (#49)
Closes #47 by implementing a simple as_dict() method for ValidatedEmail that can be called when a dict serializable object is desired
1 parent 458c9c4 commit 48840d1

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

email_validator/__init__.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,10 @@ def as_constructor(self):
156156
) \
157157
+ ")"
158158

159+
"""Convenience method for accessing ValidatedEmail as a dict"""
160+
def as_dict(self):
161+
return self.__dict__
162+
159163

160164
def validate_email(
161165
email,
@@ -536,7 +540,7 @@ def main():
536540
email = email.decode("utf8") # assume utf8 in input
537541
try:
538542
result = validate_email(email, allow_smtputf8=allow_smtputf8, check_deliverability=check_deliverability)
539-
print(json.dumps(result, indent=2, sort_keys=True, ensure_ascii=False))
543+
print(json.dumps(result.as_dict(), indent=2, sort_keys=True, ensure_ascii=False))
540544
except EmailNotValidError as e:
541545
if sys.version_info < (3,):
542546
print(unicode_class(e).encode("utf8"))

tests/test_main.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -250,6 +250,13 @@ def test_email_invalid(email_input, error_msg):
250250
assert str(exc_info.value) == error_msg
251251

252252

253+
def test_dict_accessor():
254+
input_email = "testaddr@example.com"
255+
valid_email = validate_email(input_email, check_deliverability=False)
256+
assert isinstance(valid_email.as_dict(), dict)
257+
assert valid_email.as_dict()["original_email"] == input_email
258+
259+
253260
def test_deliverability_no_records():
254261
assert validate_email_deliverability('example.com', 'example.com') == {'mx': [(0, '')], 'mx-fallback': None}
255262

0 commit comments

Comments
 (0)