F# Data: JSON Type Provider
This article demonstrates how to use the JSON Type Provider to access JSON files in a statically typed way. We first look at how the structure is inferred and then demonstrate the provider by parsing data from WorldBank and Twitter.
The JSON Type Provider provides statically typed access to JSON documents. It takes a sample document as an input (or a document containing a JSON array of samples). The generated type can then be used to read files with the same structure. If the loaded file does not match the structure of the sample, a runtime error may occur (but only when accessing e.g. non-existing element).
Introducing the provider
The type provider is located in the FSharp.Data.dll assembly. Assuming the assembly
is located in the ../../../bin directory, we can load it in F# Interactive as follows:
1: 2: |
|
Inferring types from the sample
The JsonProvider<...> takes one static parameter of type string. The parameter can
be either a sample string or a sample file (relative to the current folder or online
accessible via http or https). It is not likely that this could lead to ambiguities.
The following sample passes a small JSON string to the provider:
1: 2: 3: 4: |
|
You can see that the generated type has two properties - Age of type int and Name of
type string. The provider successfully infers the types from the sample and exposes the
fields as properties (with PascalCase name to follow standard naming conventions).
Inferring numeric types
In the previous case, the sample document simply contained an integer and so the provider
inferred the type int. Sometimes, the types in the sample document (or a list of samples)
may not match exactly. For example, a list may mix integers and floats:
1: 2: 3: |
|
When the sample is a collection, the type provider generates a type that can be used to store
all values in the sample. In this case, the resulting type is decimal, because one
of the values is not an integer. In general, the provider supports (and prefers them
in this order): int, int64, decimal and float.
Other primitive types cannot be combined into a single type. For example, if the list contains numbers and strings. In this case, the provider generates two methods that can be used to get values that match one of the types:
1: 2: 3: 4: 5: |
|
As you can see, the Mixed type has properties Numbers and Strings that
return only int and string values from the collection. This means that we get
type-safe access to the values, but not in the original order (if order matters, then
you can use the mixed.JsonValue property to get the underlying JsonValue and
process it dynamically as described in the documentation for JsonValue.
Inferring record types
Now let's look at a sample JSON document that contains a list of records. The
following example uses two records - one with name and age and the second with just
name. If a property is missing, then the provider infers it as optional.
If we want to just use the same text used for the schema at runtime, we can use the GetSamples method:
1: 2: 3: 4: 5: 6: 7: 8: |
|
The inferred type for items is a collection of (anonymous) JSON entities - each entity
has properties Name and Age. As Age is not available for all records in the sample
data set, it is inferred as option<int>. The above sample uses Option.iter to print
the value only when it is available.
In the previous case, the values of individual properties had common types - string
for the Name property and numeric type for Age. However, what if the property of
a record can have multiple different types? In that case, the type provider behaves
as follows:
1: 2: 3: 4: 5: 6: 7: |
|
Here, the Value property is either a number or a string, The type provider generates
a type that has an optional property for each possible option, so we can use
simple pattern matching on option<int> and option<string> values to distinguish
between the two options. This is similar to the handling of heterogeneous arrays.
Note that we have a GetSamples method because the sample is a JSON list. If it was a JSON
object, we would have a GetSample method instead.
More complex object type on root level
If you want the root type to be an object type, not an array, but you need more samples at root level, you can use the SampleIsList parameter. Applied to the previous example this would be:
1: 2: 3: 4: 5: |
|
Loading WorldBank data
Now let's use the type provider to process some real data. We use a data set returned by the WorldBank, which has (roughly) the following structure:
1: 2: 3: 4: 5: 6: 7: |
|
The response to a request contains an array with two items. The first item is a record
with general information about the response (page, total pages, etc.) and the second item
is another array which contains the actual data points. For every data point, we get
some information and the actual value. Note that the value is passed as a string
(for some unknown reason). It is wrapped in quotes, so the provider infers its type as
string (and we need to convert it manually).
The following sample generates type based on the data/WorldBank.json
file and loads it:
1: 2: |
|
Note that we can also load the data directly from the web both in the Load method and in
the type provider sample parameter, and there's an asynchronous AsyncLoad method available too:
1: 2: 3: 4: 5: 6: |
|
The doc is an array of heterogeneous types, so the provider generates a type
that can be used to get the record and the array, respectively. Note that the
provider infers that there is only one record and one array. We can print the data set as follows:
1: 2: 3: 4: 5: 6: 7: 8: 9: |
|
When printing the data points, some of the values might be missing (in the input, the value
is null instead of a valid number). This is another example of a heterogeneous type -
the type is either Number or some other type (representing null value). This means
that record.Value has a Number property (when the value is a number) and we can use
it to print the result only when the data point is available.
Parsing Twitter stream
We now look on how to parse tweets returned by the Twitter API.
Tweets are quite heterogeneous, so we infer the structure from a list of inputs rather than from
just a single input. To do that, we use the file data/TwitterStream.json
(containing a list of tweets) and pass an optional parameter SampleIsList=true which tells the
provider that the sample is actually a list of samples:
1: 2: 3: 4: 5: 6: |
|
After creating the Tweet type, we parse a single sample tweet and print some details about the
tweet. As you can see, the tweet.User property has been inferred as optional (meaning that a
tweet might not have an author?) so we unsafely get the value using the Value property.
The RetweetCount and Text properties may be also missing, so we also access them unsafely.
Getting and creating GitHub issues
In this example we will now also create JSON in addition to consuming it. Let's start by listing the 5 most recently updated open issues in the FSharp.Data repo.
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: |
|
And now let's create a new issue. We look into the documentation at http://developer.github.com/v3/issues/#create-an-issue and we see that we need to post a JSON value similar to this:
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: |
|
This JSON is different from what we got for each issue in the previous API call, so we'll define a new type based on this sample, create an instance, and send a POST request:
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: |
|
Using JSON provider in a library
You can use the types created by JSON type provider in a public API of a library that you are building, but there is one important thing to keep in mind - when the user references your library, the type provider will be loaded and the types will be generated at that time (the JSON provider is not currently a generative type provider). This means that the type provider will need to be able to access the sample JSON. This works fine when the sample is specified inline, but it won't work when the sample is specified as a local file (unless you distribute the samples with your library).
For this reason, the JSON provider lets you specify samples as embedded resources using the
static parameter EmbeddedResource. If you are building a library MyLib.dll, you can write:
1: 2: |
|
You still need to specify the local path, but this is only used when compiling MyLib.dll.
When a user of your library references MyLib.dll later, the JSON Type Provider will be able
to load MyLib.dll and locate the sample worldbank.json as a resource of the library. When
this succeeds, it does not attempt to find the local file and so your library can be used
without providing a local copy of the sample JSON files.
Related articles
- F# Data: JSON Parser - provides more information about working with JSON values dynamically.
- API Reference: JsonProvider type provider
- API Reference: JsonValue discriminated union
namespace FSharp
--------------------
namespace Microsoft.FSharp
namespace FSharp.Data
--------------------
namespace Microsoft.FSharp.Data
module JsonProvider
--------------------
type JsonProvider
<summary>Typed representation of a JSON document.</summary>
<param name='Sample'>Location of a JSON sample file or a string containing a sample JSON document.</param>
<param name='SampleIsList'>If true, sample should be a list of individual samples for the inference.</param>
<param name='RootName'>The name to be used to the root type. Defaults to `Root`.</param>
<param name='Culture'>The culture used for parsing numbers and dates. Defaults to the invariant culture.</param>
<param name='Encoding'>The encoding used to read the sample. You can specify either the character set name or the codepage number. Defaults to UTF8 for files, and to ISO-8859-1 the for HTTP requests, unless `charset` is specified in the `Content-Type` response header.</param>
<param name='ResolutionFolder'>A directory that is used when resolving relative file references (at design time and in hosted execution).</param>
<param name='EmbeddedResource'>When specified, the type provider first attempts to load the sample from the specified resource
(e.g. 'MyCompany.MyAssembly, resource_name.json'). This is useful when exposing types generated by the type provider.</param>
<param name='InferTypesFromValues'>If true, turns on additional type inference from values.
(e.g. type inference infers string values such as "123" as ints and values constrained to 0 and 1 as booleans.)</param>
Parses the specified JSON string
Parses the specified JSON string
from Microsoft.FSharp.Collections
from Microsoft.FSharp.Core
from Microsoft.FSharp.Core
Loads JSON from the specified uri
type DateTime =
struct
new : ticks:int64 -> DateTime + 10 overloads
member Add : value:TimeSpan -> DateTime
member AddDays : value:float -> DateTime
member AddHours : value:float -> DateTime
member AddMilliseconds : value:float -> DateTime
member AddMinutes : value:float -> DateTime
member AddMonths : months:int -> DateTime
member AddSeconds : value:float -> DateTime
member AddTicks : value:int64 -> DateTime
member AddYears : value:int -> DateTime
...
end
--------------------
System.DateTime ()
(+0 other overloads)
System.DateTime(ticks: int64) : System.DateTime
(+0 other overloads)
System.DateTime(ticks: int64, kind: System.DateTimeKind) : System.DateTime
(+0 other overloads)
System.DateTime(year: int, month: int, day: int) : System.DateTime
(+0 other overloads)
System.DateTime(year: int, month: int, day: int, calendar: System.Globalization.Calendar) : System.DateTime
(+0 other overloads)
System.DateTime(year: int, month: int, day: int, hour: int, minute: int, second: int) : System.DateTime
(+0 other overloads)
System.DateTime(year: int, month: int, day: int, hour: int, minute: int, second: int, kind: System.DateTimeKind) : System.DateTime
(+0 other overloads)
System.DateTime(year: int, month: int, day: int, hour: int, minute: int, second: int, calendar: System.Globalization.Calendar) : System.DateTime
(+0 other overloads)
System.DateTime(year: int, month: int, day: int, hour: int, minute: int, second: int, millisecond: int) : System.DateTime
(+0 other overloads)
System.DateTime(year: int, month: int, day: int, hour: int, minute: int, second: int, millisecond: int, kind: System.DateTimeKind) : System.DateTime
(+0 other overloads)
type LiteralAttribute =
inherit Attribute
new : unit -> LiteralAttribute
--------------------
new : unit -> LiteralAttribute
inherit IJsonDocument
new : title: string * body: string * assignee: string * milestone: int * labels: string [] -> Issue + 1 overload
member Assignee : string
member Body : string
member JsonValue : JsonValue
member Labels : string []
member Milestone : int
member Title : string

