Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F#: record to query string

I'm searching for an existing solution to serialize records to query strings but found nothing. I know about F#'s pretty printing, but I have no idea how to access it manually.

In common I want something like this:

type Person = {first:string; last:string}
type Group = {name:string; size:int}

let person = {first="Mary"; last="Smith"}
let personQueryString = Something.toQueryString person

let group = {name="Full"; size=345}
let groupQueryString = Something.toQueryString group

where

personQueryString -> "first=Mary&last=Smith"
groupQueryString -> "name=Full&size=345"
like image 561
Roman Dibikhin Avatar asked May 29 '26 22:05

Roman Dibikhin


1 Answers

I don't think such a function exists, but you can write one that uses Reflection:

open System.Reflection

module Something =
    let toQueryString x =
        let formatElement (pi : PropertyInfo) =
            sprintf "%s=%O" pi.Name <| pi.GetValue x
        x.GetType().GetProperties()
        |> Array.map formatElement
        |> String.concat "&"

Since it uses Reflection, it's not as efficient as specialised functions that know about the types in advance, so whether or not this is sufficient for your needs, only you know.

It produces the desired result, though:

> let person = {first="Mary"; last="Smith"};;

val person : Person = {first = "Mary";
                       last = "Smith";}

> let personQueryString = Something.toQueryString person;;

val personQueryString : string = "first=Mary&last=Smith"

> let group = {name="Full"; size=345};;

val group : Group = {name = "Full";
                     size = 345;}

> let groupQueryString = Something.toQueryString group;;

val groupQueryString : string = "name=Full&size=345"
like image 189
Mark Seemann Avatar answered Jun 01 '26 17:06

Mark Seemann