python / python/cpython

Allow JSONEncoder to handle passing unsupported dict keys through `.default()` before throwing TypeError

Abierto
#117,391 1 comentario 4 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

stdlib type-feature
Lenguaje dominante
Python
Estrellas
77.2k
Forks
35.9k
Métricas de merge de PR
Métricas de PR pendientes

Descripción

Feature or enhancement

Proposal:

Encoding a dict to JSON raises TypeError if a key is not one of the simple types natively supported by JSON (bool, None, int, float, str).

However, some other types of objects are "JSON-like" enough that users commonly use them as keys, and it would be handy to be able to dump such dicts to JSON format. For values, this is supported via the encoder's .default() method, but for keys there isn't a current way to accomplish this other than manually processing the dict to convert all such keys before passing it to JSONEncoder. It can't be handled in .default() as a dict doesn't get passed to .default().

Example objects that are not simple types but used as keys (I've used all these myself):

to_encode = {
    b"foobar": "bytes key",
    pathlib.Path("/tmp"): "Path key",
    uuid.uuid4(): "UUID key",
    ipaddress.ip_address("127.0.0.1"): "IP address key",
}

Calling json.dumps() on such a dict will raise TypeError: keys must be str, int, float, bool or None, not bytes, even if you try to subclass JSONEncoder and handle a dict's keys in .default().

I have a patch that adds an optional kwarg convert_keys that, when set, causes the encoder to pass such keys through the encoder's .default() method, and only raise an exception if that does not return one of the JSON-supported types. It defaults to off, and skipkeys still takes precedence over the new setting, so existing uses will see no change in behaviour.

I did search for discussions of this, but didn't find anything related, only other proposals like adding a JSON dunder method so any object can control its JSON serialization, which is a different approach. I believe my approach is much more similar to the way values are currently handled, and will therefore be more familiar to users.

Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Links to previous discussion of this feature:

No response

Linked PRs
  • gh-117392

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Línea de trabajo

Comienza con el manejo de claves de JSONEncoder de Python y su ruta default() existente; el issue no nombra ningún archivo de origen ni ninguna prueba. Revisa el PR vinculado gh-117392 y confirma que la conversión opcional de claves conserva el comportamiento existente, respeta skipkeys y solo produce un error cuando la conversión no da como resultado un tipo de clave compatible con JSON.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
python
Área
backend
Tipo de issue
Nueva funcionalidad
Dificultad
4/5
Tiempo estimado
3-5 días
Estado de actividad
Estancado
Claridad
Bastante claro
Aptitud para principiantes
25/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.