Learn Lua · Data formats · Lesson 1 of 4
JSON
Most data between systems travels as JSON text. json.decode turns JSON text into
tables, and json.encode turns tables back into JSON text:
local order = json.decode('{"id": "SO-1", "lines": [{"qty": 2}]}')
order.id --> "SO-1"
#order.lines --> 1
json.encode({ ok = true, count = 2 }, { sort_keys = true }) --> '{"count":2,"ok":true}'sort_keys puts the fields in alphabetical order, so the same table always gives the
same text.
What your code receives
Your code gets its data as input. The type Input line at the top of the code lists every field, and the editor uses it to suggest field names and spot typos. Here is an example. Each check sends different values, so work from the fields rather than these exact values.
input = { body = '{"id": "SO-1042", "lines": [{"qty": 2}, {"qty": 1}]}' }Steps
- Return
id: theidfrom the JSON text ininput.body. - Add
lines: how many lines the order has. - Add
reply: JSON text withacceptedset totrueand the sameid, keys sorted.
Show a hint
Decode the body once into a local and use it for every field. Build the reply as a table first, then encode it.