Read a JSON file
Task: show a cart from a JSON file, with each line's subtotal, largest first.
yaml
# Recipe: read a JSON file and add a computed field to each record.
paths:
components: ./componentsjson
[
{"id": 1, "name": "Mug", "price": 30, "qty": 4},
{"id": 2, "name": "T-shirt", "price": 80, "qty": 1},
{"id": 3, "name": "Sticker", "price": 5, "qty": 10}
]A JSON array is the list as it is. q:compute adds a field to each record; {price} and {qty} are the record's own fields.
xml
<q:component name="Cart">
<!-- A JSON array is the list as it is; each object is a record. -->
<q:data name="items" source="import/products.json" type="json">
<q:transform>
<q:compute field="subtotal" expression="{price} * {qty}" type="integer" />
<q:sort by="subtotal" order="desc" />
</q:transform>
</q:data>
<ui:window title="Cart">
<ui:table source="{items}">
<ui:column key="name" label="Item" />
<ui:column key="qty" label="Qty" />
<ui:column key="subtotal" label="Subtotal" />
</ui:table>
</ui:window>
</q:component>xml
<q:test name="each item with its subtotal, largest first" page="/">
<test:visit />
<test:expect text="Mug 4 120 T-shirt 1 80 Sticker 10 50" />
</q:test>text
tests/cart.test.q
PASS each item with its subtotal, largest first
1 passed, 0 failed