Encoders - jsonable_encoder

fastapi.encoders.jsonable_encoder

  1. jsonable_encoder(
  2. obj,
  3. include=None,
  4. exclude=None,
  5. by_alias=True,
  6. exclude_unset=False,
  7. exclude_defaults=False,
  8. exclude_none=False,
  9. custom_encoder=None,
  10. sqlalchemy_safe=True,
  11. )

Convert any object to something that can be encoded in JSON.

This is used internally by FastAPI to make sure anything you return can be encoded as JSON before it is sent to the client.

You can also use it yourself, for example to convert objects before saving them in a database that supports only JSON.

Read more about it in the FastAPI docs for JSON Compatible Encoder.

PARAMETERDESCRIPTION
obj

The input object to convert to JSON.

TYPE: Any

include

Pydantic’s include parameter, passed to Pydantic models to set the fields to include.

TYPE: Optional[IncEx] DEFAULT: None

exclude

Pydantic’s exclude parameter, passed to Pydantic models to set the fields to exclude.

TYPE: Optional[IncEx] DEFAULT: None

by_alias

Pydantic’s by_alias parameter, passed to Pydantic models to define if the output should use the alias names (when provided) or the Python attribute names. In an API, if you set an alias, it’s probably because you want to use it in the result, so you probably want to leave this set to True.

TYPE: bool DEFAULT: True

exclude_unset

Pydantic’s exclude_unset parameter, passed to Pydantic models to define if it should exclude from the output the fields that were not explicitly set (and that only had their default values).

TYPE: bool DEFAULT: False

exclude_defaults

Pydantic’s exclude_defaults parameter, passed to Pydantic models to define if it should exclude from the output the fields that had the same default value, even when they were explicitly set.

TYPE: bool DEFAULT: False

exclude_none

Pydantic’s exclude_none parameter, passed to Pydantic models to define if it should exclude from the output any fields that have a None value.

TYPE: bool DEFAULT: False

custom_encoder

Pydantic’s custom_encoder parameter, passed to Pydantic models to define a custom encoder.

TYPE: Optional[Dict[Any, Callable[[Any], Any]]] DEFAULT: None

sqlalchemy_safe

Exclude from the output any fields that start with the name _sa.

This is mainly a hack for compatibility with SQLAlchemy objects, they store internal SQLAlchemy-specific state in attributes named with _sa, and those objects can’t (and shouldn’t be) serialized to JSON.

TYPE: bool DEFAULT: True

Source code in fastapi/encoders.py

  1. 102
  2. 103
  3. 104
  4. 105
  5. 106
  6. 107
  7. 108
  8. 109
  9. 110
  10. 111
  11. 112
  12. 113
  13. 114
  14. 115
  15. 116
  16. 117
  17. 118
  18. 119
  19. 120
  20. 121
  21. 122
  22. 123
  23. 124
  24. 125
  25. 126
  26. 127
  27. 128
  28. 129
  29. 130
  30. 131
  31. 132
  32. 133
  33. 134
  34. 135
  35. 136
  36. 137
  37. 138
  38. 139
  39. 140
  40. 141
  41. 142
  42. 143
  43. 144
  44. 145
  45. 146
  46. 147
  47. 148
  48. 149
  49. 150
  50. 151
  51. 152
  52. 153
  53. 154
  54. 155
  55. 156
  56. 157
  57. 158
  58. 159
  59. 160
  60. 161
  61. 162
  62. 163
  63. 164
  64. 165
  65. 166
  66. 167
  67. 168
  68. 169
  69. 170
  70. 171
  71. 172
  72. 173
  73. 174
  74. 175
  75. 176
  76. 177
  77. 178
  78. 179
  79. 180
  80. 181
  81. 182
  82. 183
  83. 184
  84. 185
  85. 186
  86. 187
  87. 188
  88. 189
  89. 190
  90. 191
  91. 192
  92. 193
  93. 194
  94. 195
  95. 196
  96. 197
  97. 198
  98. 199
  99. 200
  100. 201
  101. 202
  102. 203
  103. 204
  104. 205
  105. 206
  106. 207
  107. 208
  108. 209
  109. 210
  110. 211
  111. 212
  112. 213
  113. 214
  114. 215
  115. 216
  116. 217
  117. 218
  118. 219
  119. 220
  120. 221
  121. 222
  122. 223
  123. 224
  124. 225
  125. 226
  126. 227
  127. 228
  128. 229
  129. 230
  130. 231
  131. 232
  132. 233
  133. 234
  134. 235
  135. 236
  136. 237
  137. 238
  138. 239
  139. 240
  140. 241
  141. 242
  142. 243
  143. 244
  144. 245
  145. 246
  146. 247
  147. 248
  148. 249
  149. 250
  150. 251
  151. 252
  152. 253
  153. 254
  154. 255
  155. 256
  156. 257
  157. 258
  158. 259
  159. 260
  160. 261
  161. 262
  162. 263
  163. 264
  164. 265
  165. 266
  166. 267
  167. 268
  168. 269
  169. 270
  170. 271
  171. 272
  172. 273
  173. 274
  174. 275
  175. 276
  176. 277
  177. 278
  178. 279
  179. 280
  180. 281
  181. 282
  182. 283
  183. 284
  184. 285
  185. 286
  186. 287
  187. 288
  188. 289
  189. 290
  190. 291
  191. 292
  192. 293
  193. 294
  194. 295
  195. 296
  196. 297
  197. 298
  198. 299
  199. 300
  200. 301
  201. 302
  202. 303
  203. 304
  204. 305
  205. 306
  206. 307
  207. 308
  208. 309
  209. 310
  210. 311
  211. 312
  212. 313
  213. 314
  214. 315
  215. 316
  216. 317
  217. 318
  218. 319
  219. 320
  220. 321
  221. 322
  222. 323
  223. 324
  224. 325
  225. 326
  226. 327
  227. 328
  228. 329
  229. 330
  230. 331
  231. 332
  232. 333
  233. 334
  234. 335
  235. 336
  236. 337
  237. 338
  238. 339
  239. 340
  240. 341
  1. def jsonableencoder(
  2. obj: Annotated[
  3. Any,
  4. Doc(
  5. “””
  6. The input object to convert to JSON.
  7. “””
  8. ),
  9. ],
  10. include: Annotated[
  11. Optional[IncEx],
  12. Doc(
  13. “””
  14. Pydantics include parameter, passed to Pydantic models to set the
  15. fields to include.
  16. “””
  17. ),
  18. ] = None,
  19. exclude: Annotated[
  20. Optional[IncEx],
  21. Doc(
  22. “””
  23. Pydantics exclude parameter, passed to Pydantic models to set the
  24. fields to exclude.
  25. “””
  26. ),
  27. ] = None,
  28. byalias: Annotated[
  29. bool,
  30. Doc(
  31. “””
  32. Pydantics by_alias parameter, passed to Pydantic models to define if
  33. the output should use the alias names (when provided) or the Python
  34. attribute names. In an API, if you set an alias, its probably because you
  35. want to use it in the result, so you probably want to leave this set to
  36. True.
  37. “””
  38. ),
  39. ] = True,
  40. excludeunset: Annotated[
  41. bool,
  42. Doc(
  43. “””
  44. Pydantics exclude_unset parameter, passed to Pydantic models to define
  45. if it should exclude from the output the fields that were not explicitly
  46. set (and that only had their default values).
  47. “””
  48. ),
  49. ] = False,
  50. excludedefaults: Annotated[
  51. bool,
  52. Doc(
  53. “””
  54. Pydantics exclude_defaults parameter, passed to Pydantic models to define
  55. if it should exclude from the output the fields that had the same default
  56. value, even when they were explicitly set.
  57. “””
  58. ),
  59. ] = False,
  60. excludenone: Annotated[
  61. bool,
  62. Doc(
  63. “””
  64. Pydantics exclude_none parameter, passed to Pydantic models to define
  65. if it should exclude from the output any fields that have a None value.
  66. “””
  67. ),
  68. ] = False,
  69. customencoder: Annotated[
  70. Optional[Dict[Any, Callable[[Any], Any]]],
  71. Doc(
  72. “””
  73. Pydantics custom_encoder parameter, passed to Pydantic models to define
  74. a custom encoder.
  75. “””
  76. ),
  77. ] = None,
  78. sqlalchemy_safe: Annotated[
  79. bool,
  80. Doc(
  81. “””
  82. Exclude from the output any fields that start with the name _sa.
  83. This is mainly a hack for compatibility with SQLAlchemy objects, they
  84. store internal SQLAlchemy-specific state in attributes named with _sa,
  85. and those objects cant (and shouldnt be) serialized to JSON.
  86. “””
  87. ),
  88. ] = True,
  89. ) -> Any:
  90. “””
  91. Convert any object to something that can be encoded in JSON.
  92. This is used internally by FastAPI to make sure anything you return can be
  93. encoded as JSON before it is sent to the client.
  94. You can also use it yourself, for example to convert objects before saving them
  95. in a database that supports only JSON.
  96. Read more about it in the
  97. FastAPI docs for JSON Compatible Encoder.
  98. “””
  99. custom_encoder = custom_encoder or {}
  100. if custom_encoder:
  101. if type(obj) in custom_encoder:
  102. return custom_encodertype(obj)
  103. else:
  104. for encoder_type, encoder_instance in custom_encoder.items():
  105. if isinstance(obj, encoder_type):
  106. return encoder_instance(obj)
  107. if include is not None and not isinstance(include, (set, dict)):
  108. include = set(include)
  109. if exclude is not None and not isinstance(exclude, (set, dict)):
  110. exclude = set(exclude)
  111. if isinstance(obj, BaseModel):
  112. # TODO: remove when deprecating Pydantic v1
  113. encoders: Dict[Any, Any] = {}
  114. if not PYDANTIC_V2:
  115. encoders = getattr(obj.__config, json_encoders, {}) # type: ignore[attr-defined]
  116. if custom_encoder:
  117. encoders.update(custom_encoder)
  118. obj_dict = _model_dump(
  119. obj,
  120. mode=json,
  121. include=include,
  122. exclude=exclude,
  123. by_alias=by_alias,
  124. exclude_unset=exclude_unset,
  125. exclude_none=exclude_none,
  126. exclude_defaults=exclude_defaults,
  127. )
  128. if __root in obj_dict:
  129. obj_dict = obj_dict[__root]
  130. return jsonable_encoder(
  131. obj_dict,
  132. exclude_none=exclude_none,
  133. exclude_defaults=exclude_defaults,
  134. # TODO: remove when deprecating Pydantic v1
  135. custom_encoder=encoders,
  136. sqlalchemy_safe=sqlalchemy_safe,
  137. )
  138. if dataclasses.is_dataclass(obj):
  139. obj_dict = dataclasses.asdict(obj)
  140. return jsonable_encoder(
  141. obj_dict,
  142. include=include,
  143. exclude=exclude,
  144. by_alias=by_alias,
  145. exclude_unset=exclude_unset,
  146. exclude_defaults=exclude_defaults,
  147. exclude_none=exclude_none,
  148. custom_encoder=custom_encoder,
  149. sqlalchemy_safe=sqlalchemy_safe,
  150. )
  151. if isinstance(obj, Enum):
  152. return obj.value
  153. if isinstance(obj, PurePath):
  154. return str(obj)
  155. if isinstance(obj, (str, int, float, type(None))):
  156. return obj
  157. if isinstance(obj, dict):
  158. encoded_dict = {}
  159. allowed_keys = set(obj.keys())
  160. if include is not None:
  161. allowed_keys &= set(include)
  162. if exclude is not None:
  163. allowed_keys -= set(exclude)
  164. for key, value in obj.items():
  165. if (
  166. (
  167. not sqlalchemy_safe
  168. or (not isinstance(key, str))
  169. or (not key.startswith(_sa))
  170. )
  171. and (value is not None or not exclude_none)
  172. and key in allowed_keys
  173. ):
  174. encoded_key = jsonable_encoder(
  175. key,
  176. by_alias=by_alias,
  177. exclude_unset=exclude_unset,
  178. exclude_none=exclude_none,
  179. custom_encoder=custom_encoder,
  180. sqlalchemy_safe=sqlalchemy_safe,
  181. )
  182. encoded_value = jsonable_encoder(
  183. value,
  184. by_alias=by_alias,
  185. exclude_unset=exclude_unset,
  186. exclude_none=exclude_none,
  187. custom_encoder=custom_encoder,
  188. sqlalchemy_safe=sqlalchemy_safe,
  189. )
  190. encoded_dict[encoded_key] = encoded_value
  191. return encoded_dict
  192. if isinstance(obj, (list, set, frozenset, GeneratorType, tuple, deque)):
  193. encoded_list = []
  194. for item in obj:
  195. encoded_list.append(
  196. jsonable_encoder(
  197. item,
  198. include=include,
  199. exclude=exclude,
  200. by_alias=by_alias,
  201. exclude_unset=exclude_unset,
  202. exclude_defaults=exclude_defaults,
  203. exclude_none=exclude_none,
  204. custom_encoder=custom_encoder,
  205. sqlalchemy_safe=sqlalchemy_safe,
  206. )
  207. )
  208. return encoded_list
  209. if type(obj) in ENCODERS_BY_TYPE:
  210. return ENCODERS_BY_TYPEtype(obj)
  211. for encoder, classes_tuple in encoders_by_class_tuples.items():
  212. if isinstance(obj, classes_tuple):
  213. return encoder(obj)
  214. try:
  215. data = dict(obj)
  216. except Exception as e:
  217. errors: List[Exception] = []
  218. errors.append(e)
  219. try:
  220. data = vars(obj)
  221. except Exception as e:
  222. errors.append(e)
  223. raise ValueError(errors) from e
  224. return jsonable_encoder(
  225. data,
  226. include=include,
  227. exclude=exclude,
  228. by_alias=by_alias,
  229. exclude_unset=exclude_unset,
  230. exclude_defaults=exclude_defaults,
  231. exclude_none=exclude_none,
  232. custom_encoder=custom_encoder,
  233. sqlalchemy_safe=sqlalchemy_safe,
  234. )