A type provider lets F# expose external data through typed members without first writing matching classes. It hooks into the compiler and infers types from a representative sample as you edit. The sample defines the expected shape; it need not be the data your application loads at runtime. section 10.3 section 10.3.2
Listing 10.4 Working the the JSON type provider
#r "nuget:FSharp.Data"
open FSharp.Data
[<Literal>] #1
let SampleJson = """{
"Brand": "Ibanez",
"Strings": "7",
"Pickups": [ "H", "S", "H" ] }"""
type GuitarJson = JsonProvider<SampleJson> #2
let sample = GuitarJson.GetSample() #3
let description = $"{sample.Brand} has {sample.Strings} strings." #4
Try the JSON example in an F# script. JsonProvider<SampleJson> exposes members such as Brand and Strings; changing Brand to Company in the sample makes the existing sample.Brand expression a compiler error. section 10.3.1
For a larger schema, put the sample in a JSON file rather than a long inline string. A provider can also read a remote sample. GetSample() or GetSamples() retrieves sample data, while Load() can read a separate runtime file that matches the inferred structure. The provider also examines sample values to infer field types. section 10.3.2
Keep the convenience without making the schema fragile:
- Shape the sample deliberately. If a JSON field can be absent, include both a row with it and a row without it so the provider can represent that possibility. section 10.3.4
- Prefer a source-controlled schema sample to a live resource you do not control: a changed or unavailable remote sample can stop compilation. section 10.3.4
- Use provided types for exploration or as data-transfer shapes, then map into richer domain types where needed. Provided types cannot generate F# records, tuples, or discriminated unions. section 10.3.4
Beyond JSON
FSharp.Data also provides CSV and HTML type providers. An HTML provider can expose a web page’s table as rows with typed members; those rows can be mapped to borough population densities and passed to Plotly.NET for a chart. section 10.3.3 section 10.4
Type providers are particularly useful for scripts, rapid prototypes, and data exploration. For application boundaries, consider whether ordinary JSON deserialization followed by explicit mapping gives you a better domain model. The provider’s typed-member experience is an F# feature; it is not supported in C#. section 10.7 section 11.2.1
