Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing an immutable object F#

I think the title of this is wrong but can't create a title that reflects, in the abstract, what I want to achieve.

I am writing a function which calls a service and retrieves data as a JSON string. The function parses the string with a JSON type provider. Under certain conditions I want to amend properties on that JSON object and then return the string of the amended object. So if the response from the call was

{"property1" : "value1","property2" : "value2", "property3": "value3" }

I want to change property3 to a new value and then return the JSON string.

If the JsonProvider was mutable this would be an exercise like:

type JsonResponse = 
        JsonProvider<""" {"property1" : "value1", 
                          "property2" : "value2",
                          "property3": "value3" } """>

let jsonResponse = JsonResponse.Parse(response)
jsonResponse.Property3 <- "new value"
jsonResponse.ToString()

However, this does not work as the property cannot be set. I am trying to ascertain the best way to resolve this. I am quite happy to initialise a new object based on the original response but with amended parameters but I am not sure if there is an easy way to achieve this.

For reference, the JSON object is much more involved than the flat example given and contains a deep hierarchy.

like image 376
AlexC Avatar asked Jun 27 '14 08:06

AlexC


1 Answers

Yes, you would need to create a new object, changing the bits you want and using the existing object's values for the rest. We added write APIs for both the XML and JSON type providers a while back. You will notice the types representing your JSON have constructors on them. You can see an example of this in use at the bottom of this link

like image 143
Ross McKinlay Avatar answered Sep 20 '22 22:09

Ross McKinlay