Can someone help me figure out how to encode a value as null?
For example, say I have a record
rec = {v1 : String, v2 : Float}
Say, value of v2 can be missing. When I send JSON to the server, I want to encode v2 as null. For example, I want to produce the following JSON string to send to the server: "{ v1 = "elm", v2 = null}". How do I do this?
I have looked at Json.Encode 0 (Json.Encode null), but that produces "null" as string containing the word null, and not null value.
The short answer is to use the JSON.Encode library, but you see to know about that already, so let’s go into more detail.
In Elm, you have to be more specific about how your JSON is supposed to look; you can’t just say “encode this” like you can in JavaScript. JSON.Encode is a module to contains functions, but it’s not a function on its own, so Json.Encode 0 won’t compile.
This snippet calls JSON.Encode.object which takes a list of tuples and creates a JSON value. Each tuple should contain a string (key) and JSON value. We get these JSON values from other functions and values in the Json.Encode library. Here we’re using Json.Encode.string (a function) and Json.Encode.null (a value*). We could also use the function for integers, booleans, or arrays – or nest objects recursively.
Thank you @mgold. I appreciate the explanation. I suppose the output "null" when I was just doing JE.null was because the "" were showing the JSON stringified object. Is that true? Anyhow, it is good to know that using Json.Encode.null within the Json.Encode.object produces the null value.
I’ve not seen this before, but I suppose it’s possible there’s a bug in how we display JSON. The real test is to pass it out of a port and see what JavaScript says it is.
Previous line outputs string “null”. It is expected behaviour of Debug.log function, to allow you differentiate null value from a string containing the letters [‘n’, ‘u’, ‘l’, ‘l’]. The browser console does the differentiation by changing the color: black is string, grey is null value. Elm seems smarter here, because formatting is lost on copy/pasting, while quotes prevail.