Serialize a JsonValue Array using F# and FSharp.Data's JsonProvider

03 February 2021

Updated: 03 September 2023

When working with the FSharp.Data.JsonProvider type provider you may encounter a need to serialize a JsonValue array

Let’s take a look at an example where this may be necessary:

First, we’ll define the type of our data using a type provider, in this case it’s connected to the following:

data/api-response.json

1
{
2
"data": [
3
{
4
"id": "id",
5
"caption": "caption",
6
"media_type": "IMAGE",
7
"media_url": "url_to_image"
8
}
9
],
10
"paging": {
11
"cursors": {
12
"before": "hash",
13
"after": "hash"
14
},
15
"next": "full_request_url"
16
}
17
}

And the F# file that’s using this as the basis for the type definition is as follows:

1
open FSharp.Data
2
3
type ApiResponse = JsonProvider<"./data/api-response.json", SampleIsList=true>

We can also create some sample data using the ApiResponse.Parse method that’s now defined on our type thanks to the JsonProvider

1
// get some sample data
2
let sampleData = ApiResponse.Parse("""{
3
"data": [
4
{
5
"id": "id",
6
"caption": "caption",
7
"media_type": "IMAGE",
8
"media_url": "url_to_image"
9
}
10
],
11
"paging": {
12
"cursors": {
13
"before": "hash",
14
"after": "hash"
15
},
16
"next": "full_request_url"
17
}
18
}""")

If you were to use the sampleData object and try to parse it to JSON you could directly call the sampleData.JsonValue.ToString() method. As designed, this immediately returns the JSON representation of the object

However, when we take a look at the sampleData.Data property, we will notice this is a Datum array, the problem here is that the array type doesn’t have JsonValue property

However, if we look at how JsonValue is defined we will see the following:

1
union JsonValue =
2
| String of string
3
| Number of decimal
4
| Float of float
5
| Record of properties : (string * JsonValue) array
6
| Array of elements : JsonValue array
7
| Boolean of bool
8
| Null

Based on this, we can see that an Array of elements can be seen as a JsonValue array, using this information, we can make use of the JsonValue.Array constructor and the JsonValue property of each of the elements of the Data property to convert the JsonValue array to a JsonValue

1
let jsonValue =
2
// get the property we want
3
sampleData.Data
4
// extract the JsonValue property from each element
5
|> Array.map (fun p -> p.JsonValue)
6
// pass into the JsonValue.Array constructor
7
|> JsonValue.Array
8
9
let json = jsonValue.ToString()