Consider the scenario where we create a record for capturing a JSON payload. (application/json
content type)
Is there any benefit of using a closed record with a JSON type rest descriptor over an open record?
Since JSON
allows any primitive types and their derived array/record (object) assignment, and the record is only used for capturing a JSON payload, restricting it as a closed record seems redundant. (Only a few types like XML
, query
(SQL) will be restricted which cannot pass from application/json
content)
E.g.:
type Person record {|
string name;
int age;
json...;
|}
vs.
type Person record {
string name;
int age;
}
2
Answers
Please consider the above code.
In here with the second type definition (open record), when you accessing the id field, you have to cast it into a json.
In that kind of scenario it will be better to use closed record with rest descriptive.
Both of these are open records.
is equivalent to
So the difference here is a rest descriptor of
json
vsanydata
.Having a more specific type is a better reflection of the possible values. Without the explicit rest descriptor (
json...
) the type says (additional/rest) field values can beanydata
(therefore, can be table and xml too), but that isn’t the case here.With just response data binding to extract only the specified fields, it wouldn’t make much of a difference either way. But, if you need to use
Person
in a context that expects ajson
value, if you open it withanydata
, you’ll have to do an extra conversion, which can be expensive.E.g.,