2

I have the following record defined in F#:

type ListingContent = 
{ from : string
  landlord_id : string
  listing_id : string
  location : string
  name : string
  pic_1_url : string
  pic_2_url : string
  pic_3_url : string
  pic_4_url : string
  pic_5_url : string
  messages : Map<string, Map<string,MessageContent>> 
  postcode : string
  price_per_night : string
  to_date : string;
}

I am using the following code:

let listings_json = JsonConvert.DeserializeObject<Types.ListingContent>(html)

to parse the following JSON:

    {  
   "from":"19/01/2018",
   "landlord_id":"YMM45tgFFvYB7rx9PhC2TE5eW6D2",
   "listing_id":"-L0pJmU9yj4hAocHjnrB",
   "location":"Edinburgh",
   "name":"dan",
   "pic_1_url":"https://firebasestorage.googleapis.com/v0/b/....",
   "pic_2_url":"https://firebasestorage.googleapis.com/v0/b/....",
   "pic_3_url":"https://firebasestorage.googleapis.com/v0/b/....",
   "pic_4_url":"https://firebasestorage.googleapis.com/v0/b/....",
   "pic_5_url":"https://firebasestorage.googleapis.com/v0/b/....",
   "postcode":"....",
   "price_per_night":"£32",
   "to":"19/01/2019"
}

This parses everything fine except the to field, because I am using to_date in my record, it parses to null... to is a keyword in F# therefore I cannot use it in my record definition. I can't really change the JSON in the database at this point. Is there any workaround around this?

Alk
  • 5,215
  • 8
  • 47
  • 116

2 Answers2

3

You can use a keyword as identifier by enclosing it in double backticks:

``to``: string

The backticks themselves will not become part of the identifier, only what's inside of them. This way, the JSON library will see a field named "to" and you will be able to refer to it from F# as listingContent.``to``

This trick also works for identifiers with spaces and other non-identifier characters:

let ``some identifier`` = 42
let ``007`` = "Bond"

Alternatively, you can tell JSON.NET itself to use a different name for the property via the JsonProperty attribute:

[<JsonProperty "to">] to_date : string
dbc
  • 104,963
  • 20
  • 228
  • 340
Fyodor Soikin
  • 78,590
  • 9
  • 125
  • 172
  • Thanks guys, you both posted the same thing so I'll upvote both and accept the first answer. :) – Alk Jan 28 '18 at 16:59
2

Try escaping the name with backticks:

``to`` : string
Taylor Wood
  • 15,886
  • 1
  • 20
  • 37