{"id":818,"date":"2024-02-23T11:06:28","date_gmt":"2024-02-23T11:06:28","guid":{"rendered":"https:\/\/learnpython.elegantwallp.com\/?p=818"},"modified":"2024-02-23T11:06:29","modified_gmt":"2024-02-23T11:06:29","slug":"json-compatible-encoder","status":"publish","type":"post","link":"https:\/\/learnpython.elegantwallp.com\/2024\/02\/23\/json-compatible-encoder\/","title":{"rendered":"JSON Compatible Encoder"},"content":{"rendered":"\n<p>There are some cases where you might need to convert a data type (like a Pydantic model) to something compatible with JSON (like a&nbsp;<code>dict<\/code>,&nbsp;<code>list<\/code>, etc).<\/p>\n\n\n\n<p>For example, if you need to store it in a database.<\/p>\n\n\n\n<p>For that,&nbsp;<strong>FastAPI<\/strong>&nbsp;provides a&nbsp;<code>jsonable_encoder()<\/code>&nbsp;function.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"using-the-jsonable_encoder\">Using the\u00a0<code>jsonable_encoder<\/code><\/h2>\n\n\n\n<p>Let&#8217;s imagine that you have a database&nbsp;<code>fake_db<\/code>&nbsp;that only receives JSON compatible data.<\/p>\n\n\n\n<p>For example, it doesn&#8217;t receive&nbsp;<code>datetime<\/code>&nbsp;objects, as those are not compatible with JSON.<\/p>\n\n\n\n<p>So, a&nbsp;<code>datetime<\/code>&nbsp;object would have to be converted to a&nbsp;<code>str<\/code>&nbsp;containing the data in&nbsp;<a href=\"https:\/\/en.wikipedia.org\/wiki\/ISO_8601\" target=\"_blank\" rel=\"noreferrer noopener\">ISO format<\/a>.<\/p>\n\n\n\n<p>The same way, this database wouldn&#8217;t receive a Pydantic model (an object with attributes), only a&nbsp;<code>dict<\/code>.<\/p>\n\n\n\n<p>You can use&nbsp;<code>jsonable_encoder<\/code>&nbsp;for that.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>It receives an object, like a Pydantic model, and returns a JSON compatible version:Python 3.10+Python 3.8+<code>from datetime import datetime from fastapi import FastAPI from fastapi.encoders import jsonable_encoder from pydantic import BaseModel fake_db = {} class Item(BaseModel): title: str timestamp: datetime description: str | None = None app = FastAPI() @app.put(\"\/items\/{id}\") def update_item(id: str, item: Item): json_compatible_item_data = jsonable_encoder(item) fake_db&#91;id] = json_compatible_item_data<\/code><\/code><\/pre>\n\n\n\n<p>In this example, it would convert the Pydantic model to a&nbsp;<code>dict<\/code>, and the&nbsp;<code>datetime<\/code>&nbsp;to a&nbsp;<code>str<\/code>.<\/p>\n\n\n\n<p>The result of calling it is something that can be encoded with the Python standard&nbsp;<a href=\"https:\/\/docs.python.org\/3\/library\/json.html#json.dumps\" target=\"_blank\" rel=\"noreferrer noopener\"><code>json.dumps()<\/code><\/a>.<\/p>\n\n\n\n<p>It doesn&#8217;t return a large&nbsp;<code>str<\/code>&nbsp;containing the data in JSON format (as a string). It returns a Python standard data structure (e.g. a&nbsp;<code>dict<\/code>) with values and sub-values that are all compatible with JSON.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>There are some cases where you might need to convert a data type (like a Pydantic model) to something compatible with JSON (like a&nbsp;dict,&nbsp;list, etc). For example, if you need to store it in a database. For that,&nbsp;FastAPI&nbsp;provides a&nbsp;jsonable_encoder()&nbsp;function. Using the\u00a0jsonable_encoder Let&#8217;s imagine that you have a database&nbsp;fake_db&nbsp;that only receives JSON compatible data. For example, [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[90],"tags":[],"class_list":["post-818","post","type-post","status-publish","format-standard","hentry","category-fast-api"],"_links":{"self":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts\/818","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/comments?post=818"}],"version-history":[{"count":1,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts\/818\/revisions"}],"predecessor-version":[{"id":819,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts\/818\/revisions\/819"}],"wp:attachment":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/media?parent=818"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/categories?post=818"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/tags?post=818"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}