Skip to content
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

Make CustomJSONEncoder a documented public API #1983

Open
simonw opened this issue Jan 9, 2023 · 3 comments · May be fixed by #1996
Open

Make CustomJSONEncoder a documented public API #1983

simonw opened this issue Jan 9, 2023 · 3 comments · May be fixed by #1996

Comments

@simonw
Copy link
Owner

simonw commented Jan 9, 2023

It's used by datasette-geojson here: eyeseast/datasette-geojson@902bf13

@simonw
Copy link
Owner Author

simonw commented Jan 9, 2023

class CustomJSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, sqlite3.Row):
return tuple(obj)
if isinstance(obj, sqlite3.Cursor):
return list(obj)
if isinstance(obj, bytes):
# Does it encode to utf8?
try:
return obj.decode("utf8")
except UnicodeDecodeError:
return {
"$base64": True,
"encoded": base64.b64encode(obj).decode("latin1"),
}
return json.JSONEncoder.default(self, obj)

@simonw
Copy link
Owner Author

simonw commented Jan 9, 2023

I had forgotten this had special handling for cursors!

The default representation of a row as a tuple rather than a dictionary might not be the right thing to do based on:

@eyeseast
Copy link
Contributor

eyeseast commented Jan 9, 2023

Yes please, and thank you. I realized I was maybe getting myself in trouble using that, but I think it's a good way to standardize JSON handling.

@eyeseast eyeseast linked a pull request Jan 18, 2023 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants