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:

LUA
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.

LUA
input = { body = '{"id": "SO-1042", "lines": [{"qty": 2}, {"qty": 1}]}' }

Steps

  1. Return id: the id from the JSON text in input.body.
  2. Add lines: how many lines the order has.
  3. Add reply: JSON text with accepted set to true and the same id, 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.