Skip to main content
Version: Next

Json Module

Hosted interpreter permissions: Every function and value on this page requires no host permissions. Higher-order functions still enforce the requirements of their callbacks. These checks do not apply to CLI execution or compilation. See Host permissions.

Use Json to convert between FScript values and JSON text.

Json.deserialize<'a> : string -> 'a option​

None

Pass the target type in angle brackets. The result is an option of that type. FScript can also infer the target when an expected result type is available.

type Settings = { Port: int; Label: string option }
let settings = Json.deserialize<Settings> "{\"Port\":8080}"
match settings with
| Some value -> Console.writeLine $"port={value.Port}, label={value.Label}"
| None -> Console.writeLine "invalid settings"

Generic wrappers can forward their type argument.

let decode<'a> json : 'a option = Json.deserialize<'a> json
let ports = decode<int list> "[8080,8081]"

Malformed JSON, incompatible values, or unsupported target types return None.

Target field/valueJSON decoding
string, int, float, boolCorresponding JSON scalar; integers must fit signed 64 bits
unitProduces ()
'a listJSON array; every element must decode
TupleJSON array with exactly the tuple's arity
'a optionnull becomes None; other values decode as Some
Ordinary record, including generic and recursive recordsJSON object; field names are case-sensitive; extra properties are ignored
MapJSON object; property names decode as string, int, or bool keys

Missing record fields are allowed only for option fields, which become None. A failed nested conversion fails the entire result. Union types, union map keys, functions, tasks, and host-managed types are unsupported decoding targets. Decoding cannot manufacture opaque host state, including inside a record or container.

Json.serialize : 'a -> string option​

None

Returns JSON text when the entire value is serializable.

let text = Json.serialize { Port = 8080; Label = Some "api" }
// Some "{\"Label\":\"api\",\"Port\":8080}"
ValueJSON encoding
Strings, finite numbers, booleansJSON scalars
() and Nonenull
Some valueEncoding of value
Lists and tuplesJSON arrays
RecordsJSON objects
Maps with string, int, or bool keysJSON objects; integer and boolean keys become property names
Host-managed valuesVisible fields only, as a JSON object

A union value, union-keyed map, function, task, or type token anywhere in the value makes serialization return None. Opaque payloads and host-type metadata are never serialized. Non-finite floating-point values are not suitable for portable JSON round trips.

Options and tuples lose their FScript type information in JSON; use the intended target type when decoding. This API does not promise arbitrary value round trips.