|
| 1 | +# JSON Serialization with Fable.Python |
| 2 | + |
| 3 | +This document explains how to properly serialize F# types to JSON when using Fable.Python. |
| 4 | + |
| 5 | +## The Problem |
| 6 | + |
| 7 | +When Fable compiles F# to Python, certain types are not native Python types: |
| 8 | + |
| 9 | +| F# Type | Fable Python Type | Native Python? | |
| 10 | +| ---------------- | -------------------------- | -------------- | |
| 11 | +| `int` | `Int32` | No | |
| 12 | +| `int64` | `Int64` | No | |
| 13 | +| `float32` | `Float32` | No | |
| 14 | +| F# record | Class with `__slots__` | No | |
| 15 | +| F# union | Class with `tag`, `fields` | No | |
| 16 | +| F# array | `FSharpArray` | No | |
| 17 | +| `ResizeArray<T>` | `list` | Yes | |
| 18 | +| `nativeint` | `int` | Yes | |
| 19 | +| `string` | `str` | Yes | |
| 20 | + |
| 21 | +Python's standard `json.dumps()` and web framework serializers (Flask's `jsonify`, FastAPI's `jsonable_encoder`) don't know how to serialize these Fable-specific types. |
| 22 | + |
| 23 | +### Why Can't Fable's Int32 Just Inherit from Python's int? |
| 24 | + |
| 25 | +Fable.Python uses [PyO3](https://pyo3.rs/) for its runtime. Due to [PyO3 limitations](https://github.com/PyO3/pyo3/issues/991), it's not possible to create a Rust type that subclasses Python's immutable `int` type. This means `Int32` is a separate type that needs special handling during serialization. |
| 26 | + |
| 27 | +## The Solution: fableDefault |
| 28 | + |
| 29 | +The `Fable.Python.Json` module provides a `fableDefault` function that handles Fable types: |
| 30 | + |
| 31 | +```fsharp |
| 32 | +open Fable.Python.Json |
| 33 | +
|
| 34 | +// Use the convenience function (recommended) |
| 35 | +let jsonStr = dumps myObject |
| 36 | +
|
| 37 | +// Or use json.dumps with fableDefault explicitly |
| 38 | +let jsonStr = json.dumps(myObject, ``default`` = fableDefault) |
| 39 | +
|
| 40 | +// With indentation |
| 41 | +let prettyJson = dumpsIndented myObject 2 |
| 42 | +``` |
| 43 | + |
| 44 | +### What fableDefault Handles |
| 45 | + |
| 46 | +| Type | Serialization | |
| 47 | +| ------------------------------------- | ------------------------------------------- | |
| 48 | +| `Int8`, `Int16`, `Int32`, `Int64` | → Python `int` | |
| 49 | +| `UInt8`, `UInt16`, `UInt32`, `UInt64` | → Python `int` | |
| 50 | +| `Float32`, `Float64` | → Python `float` | |
| 51 | +| F# Records (with `__slots__`) | → Python `dict` | |
| 52 | +| F# Unions (with `tag`, `fields`) | → `["CaseName", ...fields]` or `"CaseName"` | |
| 53 | + |
| 54 | +## Usage Examples |
| 55 | + |
| 56 | +### Basic Serialization |
| 57 | + |
| 58 | +```fsharp |
| 59 | +open Fable.Python.Json |
| 60 | +
|
| 61 | +// Anonymous record with F# int (compiles to Int32) |
| 62 | +let data = {| id = 42; name = "Alice" |} |
| 63 | +let json = dumps data |
| 64 | +// Output: {"id": 42, "name": "Alice"} |
| 65 | +
|
| 66 | +// F# record |
| 67 | +type User = { Id: int; Name: string } |
| 68 | +let user = { Id = 1; Name = "Bob" } |
| 69 | +let json = dumps user |
| 70 | +// Output: {"Id": 1, "Name": "Bob"} |
| 71 | +
|
| 72 | +// F# discriminated union |
| 73 | +type Status = Active | Inactive | Pending of string |
| 74 | +let status = Pending "review" |
| 75 | +let json = dumps status |
| 76 | +// Output: ["Pending", "review"] |
| 77 | +``` |
| 78 | + |
| 79 | +### With Web Frameworks |
| 80 | + |
| 81 | +#### Flask |
| 82 | + |
| 83 | +Flask's `jsonify` does **not** handle Fable types. Use `dumps` from `Fable.Python.Json`: |
| 84 | + |
| 85 | +```fsharp |
| 86 | +open Fable.Python.Flask |
| 87 | +open Fable.Python.Json |
| 88 | +
|
| 89 | +[<APIClass>] |
| 90 | +type Routes() = |
| 91 | + [<Get("/users/<int:user_id>")>] |
| 92 | + static member get_user(user_id: int) : string = |
| 93 | + // Use dumps for Fable type support |
| 94 | + dumps {| id = user_id; name = "Alice" |} |
| 95 | +
|
| 96 | + [<Get("/simple")>] |
| 97 | + static member simple() : obj = |
| 98 | + // jsonify works ONLY with native Python types |
| 99 | + jsonify {| message = "Hello"; count = 42n |} // 'n' suffix = native int |
| 100 | +``` |
| 101 | + |
| 102 | +#### FastAPI |
| 103 | + |
| 104 | +FastAPI's `jsonable_encoder` does **not** handle Fable types in anonymous records. You have two options: |
| 105 | + |
| 106 | +**Option 1: Use Pydantic models** (recommended for FastAPI) |
| 107 | + |
| 108 | +```fsharp |
| 109 | +open Fable.Python.FastAPI |
| 110 | +open Fable.Python.Pydantic |
| 111 | +
|
| 112 | +[<Py.ClassAttributes(style = Py.ClassAttributeStyle.Attributes, init = false)>] |
| 113 | +type UserResponse(Id: int, Name: string) = |
| 114 | + inherit BaseModel() |
| 115 | + member val Id: int = Id with get, set |
| 116 | + member val Name: string = Name with get, set |
| 117 | +
|
| 118 | +[<APIClass>] |
| 119 | +type API() = |
| 120 | + [<Get("/users/{user_id}")>] |
| 121 | + static member get_user(user_id: int) : UserResponse = |
| 122 | + UserResponse(Id = user_id, Name = "Alice") // Works! Pydantic handles Int32 |
| 123 | +``` |
| 124 | + |
| 125 | +**Option 2: Use nativeint for anonymous records** |
| 126 | + |
| 127 | +```fsharp |
| 128 | +[<Delete("/items/{item_id}")>] |
| 129 | +static member delete_item(item_id: int) : obj = |
| 130 | + {| status = "deleted"; id = nativeint item_id |} // Convert to native int |
| 131 | +``` |
| 132 | + |
| 133 | +### Collections |
| 134 | + |
| 135 | +Use `ResizeArray<T>` instead of F# arrays for web API responses: |
| 136 | + |
| 137 | +```fsharp |
| 138 | +// Good - ResizeArray compiles to Python list |
| 139 | +let users = ResizeArray<User>() |
| 140 | +users.Add(User(Id = 1, Name = "Alice")) |
| 141 | +let json = dumps users |
| 142 | +
|
| 143 | +// Avoid - F# array compiles to FSharpArray |
| 144 | +let users = [| User(Id = 1, Name = "Alice") |] // May not serialize correctly |
| 145 | +``` |
| 146 | + |
| 147 | +## Quick Reference |
| 148 | + |
| 149 | +| Scenario | Solution | |
| 150 | +|----------|----------| |
| 151 | +| JSON API with Fable types | Use `Fable.Python.Json.dumps` | |
| 152 | +| Flask endpoint | Use `dumps` instead of `jsonify` | |
| 153 | +| FastAPI endpoint | Use Pydantic models or `nativeint` | |
| 154 | +| Int literals in anonymous records | Use `42n` suffix for native int | |
| 155 | +| Collections in API responses | Use `ResizeArray<T>` | |
| 156 | +| F# array needed | Convert with `ResizeArray(myArray)` | |
| 157 | + |
| 158 | +## API Reference |
| 159 | + |
| 160 | +```fsharp |
| 161 | +module Fable.Python.Json |
| 162 | +
|
| 163 | +/// Default serializer for Fable types |
| 164 | +val fableDefault: obj -> obj |
| 165 | +
|
| 166 | +/// Serialize to JSON with Fable type support |
| 167 | +val dumps: obj -> string |
| 168 | +
|
| 169 | +/// Serialize to JSON with indentation |
| 170 | +val dumpsIndented: obj -> int -> string |
| 171 | +
|
| 172 | +/// Serialize to file with Fable type support |
| 173 | +val dump: obj -> TextIOWrapper -> unit |
| 174 | +
|
| 175 | +/// Serialize to file with indentation |
| 176 | +val dumpIndented: obj -> TextIOWrapper -> int -> unit |
| 177 | +
|
| 178 | +/// Raw Python json module (use with fableDefault for Fable types) |
| 179 | +val json: IExports |
| 180 | +``` |
| 181 | + |
| 182 | +## Further Reading |
| 183 | + |
| 184 | +- [PyO3 Issue #991](https://github.com/PyO3/pyo3/issues/991) - Why Int32 can't subclass Python's int |
| 185 | +- [Python json module](https://docs.python.org/3/library/json.html) - Standard library documentation |
| 186 | +- [Pydantic](https://docs.pydantic.dev/) - Data validation for Python (works with Fable's Int32) |
0 commit comments