Search code examples
f#type-providers

F# TypeInitializationException Thrown Parsing Json File


Playing around with F# Type Providers and have not got too far. I have the following json file (called PriceDemand.json):

[
  {
    "intervalDate": "2018-01-22T00:00:00+11:00",
    "regionId": "NSW1",
    "rrp": 114.17,
    "totalDemand": 12338.04
  },
  {
    "intervalDate": "2018-01-22T00:00:00+11:00",
    "regionId": "NSW1",
    "rrp": 113.41,
    "totalDemand": 12334.98
  }
]

I've written the following code to process it:

open FSharp.Data
open System

type PriceDemand = JsonProvider<"PriceDemand.json">
let data = PriceDemand.Parse("PriceDemand.json")

[<EntryPoint>]
let main argv =


    data |> Seq.iter (fun v -> printf "%s" v.RegionId)

    Console.ReadLine() |> ignore
    0 // return an integer exit code

I have intellisense for the PriceDemand type, but the following TypeInitializationExceptionexception is being thrown:

Invalid JSON starting at character 0,
snippet =
---- PriceDemand
----- json =
------ PriceDemand.json

Any ideas what I am doing wrong?


Solution

  • You're calling .Parse where you should be calling .Load. The string "PriceDemand.json" is being parsed as JSON, which is not valid. If you change the call to let data = PriceDemand.Load("PriceDemand.json"), it should work fine.