I have a record
type MyType = {
Name : string
Description : string
OtherField : string
}
I'd like to remove some of the fields before I serialize to JSON. How can I do this?
I have a record
type MyType = {
Name : string
Description : string
OtherField : string
}
I'd like to remove some of the fields before I serialize to JSON. How can I do this?
Let's assume you're starting with
let object = {
Name = "hi"
Description = "ho"
OtherField = "there"
}
#r "nuget:Newtonsoft.Json"
open Newtonsoft.Json
open Newtonsoft.Json.Linq
let json = JsonConvert.SerializeObject object
let fieldsToRemove = [|
"Name"
"OtherField"
|]
Here's a function that takes an object as input
let removeFromObject (fields : string []) object =
let jToken = JToken.FromObject object
let allFields = jToken.Children() |> Seq.map (fun t -> t :?> JProperty)
let remainingFields = allFields |> Seq.filter (fun f -> Array.contains f.Name fields |> not)
let newObject = JObject remainingFields
let newJson = JsonConvert.SerializeObject(newObject, Formatting.Indented)
newJson
removeFromObject fieldsToRemove object
And here an adapter for taking a string
let removeFromString (fields : string []) json =
let jToken = JObject.Parse json :> JToken
removeFromObject fields jToken
removeFromString fieldsToRemove json
This was inspired by JSON.NET how to remove nodes