Place the calculation after its inputs
JsonLogic expresses rules in JSON. Add a calculation item to a sequential survey block after the questions it reads and before the item that uses its result.
answers.<id>reads an earlier answer. A numeric text question supplies a number, a single choice supplies its option code, and a multiple choice supplies a list of selected codes.calculations.<id>reads an earlier calculation. Give each calculation an ID and a result type, such asnumberornumber_list.- Use the optional
descriptionto explain the rule in Survey Content → Flow.
For visibility rules and standard repeats, see Data & flows.
Calculate a trip budget and show the total
A school trip costs €60 for transport plus €12 per participant. With 10 participants, the total is €180. Put the summary at the end of the block so respondents can review the amount before submitting.
“Ask how many people are coming. Add €60 for transport and €12 per person. Show the total before submitting and update it if I go back and change the group size.”
After a numeric text question with ID participants and a minimum of 1, add these two items to the block's items array.
[
{
"type": "calculation",
"id": "total",
"result_type": "number",
"description": "Transport plus the cost per participant.",
"expression": {
"type": "expression",
"expression_value": {
"+": [60, {"*": [12, {"var": "answers.participants"}]}]
}
}
},
{
"type": "summary",
"id": "budget_summary",
"title": "Trip budget",
"rows": [{
"label": "Total",
"currency": "EUR",
"value": {
"type": "expression",
"expression_value": {"var": "calculations.total"}
}
}]
}
]Use + to add known values and reduce with + and an initial value of 0 to sum a list of variable length. For example, {"reduce": [[12, 8, 5], {"+": [{"var": "accumulator"}, {"var": "current"}]}, 0]} returns 25.
For other numeric rules, {"sqrt": [9]} returns 3 and {"pow": [2, 3]} returns 8. pow accepts integer exponents from −1000 to 1000.
Generate a new set of answer choices
Ask a respondent to choose three garments and three colours. Shuffle the selected colours and pair one with each garment. The next question can offer choices like “Hat · Red”, “Shoes · Green” and “T-shirt · Blue”.
“Ask me to pick three garments and three colours. Randomly assign one of my colours to each garment, then ask me which combination I prefer.”
Start with two multiple-choice questions, clothes and colors, that each require exactly three selections. Define favorite as a single-choice question with its options supplied by the flow. Add these items after the two source questions.
[
{
"type": "calculation",
"id": "looks",
"result_type": "pair_list",
"expression": {
"type": "expression",
"expression_value": {
"zip": [
{"var": "answers.clothes"},
{"shuffle": [{"var": "answers.colors"}]}
]
}
}
},
{
"type": "question",
"question": "favorite",
"option_source": {
"type": "calculation",
"calculation": "looks",
"question": "clothes",
"pair_with": "colors"
}
}
]Dayalogs takes the labels from the source questions and saves the code of the chosen pair. Codes in each source catalogue must be integers from 0 to 999, with at most 4096 possible pairs across both catalogues.
For a flat shortlist, return a number_list of selected option codes. Use that result as an option_source to show choices or as a repeat.source to ask one follow-up per item.
Check the result in preview
- Try the normal path, then go back and change an answer. The summary uses the latest answers. A random choice uses the same draw for the same inputs within the attempt.
- Try unanswered inputs if the source questions are optional. A summary shows a dash for an unavailable value, and an empty or unavailable list skips the dynamic follow-up.
- Inspect the calculation in Survey Content → Flow. Named calculation results are temporary. The response retains answers to the questions shown.
Operator catalogue
Rows marked Dayalogs are extensions to JsonLogic.
References and logic
| Operator | Inputs and result | Example |
|---|---|---|
var |
Read a declared reference. An optional same-type fallback applies when the value is unavailable. List positions start at zero. | {"var":["answers.current_age",0]} |
missing |
Return unavailable keys from a list of declared answers.<code> references. Zero and false are present. |
{"missing":["answers.current_age","answers.group_code"]} |
missing_some |
Take a non-negative integer minimum and a list of answer references. Return an empty list when enough answers are available. Otherwise return the unavailable keys. | {"missing_some":[1,["answers.current_age","answers.group_code"]]} |
if |
Evaluate condition/result pairs in order, with an optional last fallback. Evaluate only the selected result. Results must share a type. An unavailable condition yields an unavailable result. | {"if":[true,5,0]} |
?: |
Alias for if. Prefer if when authoring. |
{"?:":[false,5,0]} |
and |
Return the first falsy operand, or the last result. Operands share a type. | {"and":[true,false]} |
or |
Return the first truthy operand, or the last result. Operands share a type. | {"or":[false,true]} |
! |
Return true when the operand is falsy. | {"!":[0]} |
!! |
Convert the operand to a boolean. | {"!!":["0"]} |
Zero, false, empty text, empty lists and unavailable values are falsy. The
text "0" is truthy. Lists of keys for missing and missing_some can
be built with literals, merge or if. The keys must be known when the survey
is validated.
Comparisons
| Operator | Inputs and result | Example |
|---|---|---|
== |
Loose equality of two scalars. A number can equal a numeric string or boolean. | {"==":[2,"2"]} |
!= |
Negation of loose equality. | {"!=":[2,"3"]} |
=== |
Strict equality of two scalars, including their type. | {"===":[2,2]} |
!== |
Negation of strict equality. | {"!==":[2,"2"]} |
< |
Strictly ascending comparison of two or three numbers. | {"<":[1,2,3]} |
<= |
Ascending comparison that allows equal neighbours. Takes two or three numbers. | {"<=":[1,2,2]} |
> |
Strictly descending comparison of two or three numbers. | {">":[3,2,1]} |
>= |
Descending comparison that allows equal neighbours. Takes two or three numbers. | {">=":[3,3,2]} |
Strict equality preserves the distinction between text and numbers.
Numbers
| Operator | Inputs and result | Example |
|---|---|---|
min |
Return the smallest of one or more numbers. | {"min":[3,2,4]} |
max |
Return the largest of one or more numbers. | {"max":[3,2,4]} |
+ |
Add one or more numbers. | {"+":[0.1,0.2]} |
- |
Negate one number or subtract the second from the first. | {"-":[7,2]} |
* |
Multiply one or more numbers. | {"*":[4,2]} |
/ |
Divide the first number by the second. | {"/":[10,4]} |
% |
Return the remainder after division by the second number. | {"%":[10,4]} |
abs Dayalogs |
Return the magnitude of an exact decimal. | {"abs":[-12.5]} |
round Dayalogs |
Round to 0–3 decimal places, with zero as the default and ties away from zero. Invalid places yield an unavailable value. | {"round":[-1.235,2]} |
floor Dayalogs |
Return the largest integer less than or equal to the number. | {"floor":[-1.2]} |
ceil Dayalogs |
Return the smallest integer greater than or equal to the number. | {"ceil":[-1.2]} |
sqrt Dayalogs |
Return the non-negative square root of a non-negative number. A negative input yields an unavailable value. | {"sqrt":[2]} |
pow Dayalogs |
Raise a number to an integer exponent from −1000 to 1000. Negative exponents compute reciprocals. An out-of-range or fractional exponent, or zero raised to a negative exponent, yields an unavailable value. | {"pow":[2,-4]} |
Arithmetic uses exact decimals with up to three fractional digits and rounds ties away from zero. Division by zero and overflow yield an unavailable result. A numeric string in an operand slot that requires a number acts as an exact decimal. Text retains leading zeros.
sqrt and pow round the final result to the same three decimal places.
An exponent of zero gives one, including when the base is zero. The magnitude
of each pow exponent counts towards the shared evaluation limit.
Lists
| Operator | Inputs and result | Example |
|---|---|---|
map |
Apply a rule to each list item and return a list of same-type scalar results. | {"map":[[1,2],{"*":[{"var":""},3]}]} |
filter |
Keep the list items for which the rule is truthy, in the original order. | {"filter":[[1,2,3],{">":[{"var":""},1]}]} |
all |
Test whether the rule is truthy for every item. An empty list gives false. | {"all":[[1,2],{">":[{"var":""},0]}]} |
none |
Test whether the rule is truthy for zero items. An empty list gives true. | {"none":[[1,2],{"===":[{"var":""},0]}]} |
some |
Test whether the rule is truthy for at least one item. An empty list gives false. | {"some":[[1,2],{"===":[{"var":""},2]}]} |
reduce |
Accumulate a scalar or list using a rule and a same-type initial value. An empty list gives the initial value. | {"reduce":[[1,2],{"+":[{"var":"accumulator"},{"var":"current"}]},0]} |
merge |
Append scalars and list items of the same element type, in order. | {"merge":[1,[2,3]]} |
in |
Test strict membership in a list or substring membership in text. | {"in":[2,[1,2,3]]} |
count Dayalogs |
Count the items in a list of numbers, text or booleans, including duplicates. An empty list returns zero. An unavailable list yields an unavailable result. | {"count":[[1,2,2]]} |
shuffle Dayalogs |
Reorder a list without replacement. A server-issued seed keeps the same relative order for the same items within an attempt. The list type, items and duplicates are preserved. | {"shuffle":[[1,2,3]]} |
take Dayalogs |
Return up to the first N items of a list. N is a non-negative integer. Zero gives an empty list. A negative or fractional N yields an unavailable result. | {"take":[[1,2,3],2]} |
zip Dayalogs |
Pair items at matching positions in two lists of scalars. Stops at the shorter list and returns a pair_list. |
{"zip":[[1,2],["red","blue","green"]]} |
unique Dayalogs |
Keep the first occurrence of each value or pair, preserving order and types. | {"unique":[[2,1,2,3]]} |
sort Dayalogs |
Sort a list in ascending order by default. Pass "desc" to reverse it. Numbers compare by exact value, strings by Unicode code point and booleans with false first. Pairs compare by their first component and then by their second. |
{"sort":[[10,2,1],"desc"]} |
In a map, filter, all, none or some rule, {"var":""} reads the
current item. In reduce, the names are current and accumulator. Each
loop has its own locals. In a loop over pairs, use first and second to
read the components in map, filter and reduce. An unavailable input
list yields an unavailable result for the Dayalogs list extensions.
shuffle, take, unique and sort accept pair lists and preserve the
list type. Ascending sort puts null items last. Descending sort puts them
first.
Text
| Operator | Inputs and result | Example |
|---|---|---|
cat |
Concatenate scalars into text. | {"cat":["Group ",2]} |
substr |
Extract UTF-8 text given an integer start and optional integer length. Positions start at zero. A negative start counts from the end. A negative length excludes characters from the end. | {"substr":["Tòquio",0,2]} |
trim Dayalogs |
Remove Unicode whitespace from the beginning and end of a string. Interior whitespace is preserved. | {"trim":[" Tòquio "]} |
lower Dayalogs |
Convert UTF-8 text to lowercase using Unicode case mapping. | {"lower":["TÒQUIO"]} |
upper Dayalogs |
Convert UTF-8 text to uppercase using Unicode case mapping. | {"upper":["Tòquio"]} |
length Dayalogs |
Count Unicode code points in text. Use count for list length. |
{"length":["Tòquio"]} |