Skip to content
This repository has been archived by the owner on Jan 12, 2023. It is now read-only.

4. Transient and constant fields, default value

Richard Jonas edited this page May 10, 2016 · 3 revisions

Override simple values

When we don't want to include something in the JSON because it doesn't make sense on the client side (Erlang PID for example) we can skip that field. Also we can create constant fields and specify sensible defaults during decoding in case of the JSON to be decoded not have a field but it is required in the record.

Skip rule and default values

To skip a value, we need to define a skip field rule in the rule.

-json(session, {string, id}, {skip, pid, [{default, undefined}]},
               {number, age, [{default, 18}]}).

to_json({session, "111-222-333", self(), 22}).

will result in a JSON like this

{
    "id": "111-222-333",
    "age": 22
}

The default rule makes sense when we need to decode JSON and create a record. Let us say we have a poorly specified JSON, and see what ejson will generate.

{
    "id": "xxx-yyy-zzz"
}

Pid and age fields are missing, but since we specified default values ejson will use them during decoding. So the resulted record is

%% We need to specify the expected type here.
from(Json, session).
{session, "xxx-yyy-zzz", undefined, 18}.

Constant fields

const rule is very similar to skip rule but const rule will put values in the JSON.

-json({event, {const, type, "sms", [{default, "sms"}]}, {string, text}}).

to_json({event, "don't know", "Text message"}).
{
    "type": "sms",
    "text": "Text message"
}

And during decoding if type is missing it will use the default value which is sms in the rule.

Clone this wiki locally