读取 JSON 文件
机器翻译
本页由英文原文机器翻译而来,尚未经过母语审校,欢迎在 GitHub 上提出修改。内容如有出入,以英文原文为准。
任务: 根据一个 JSON 文件显示购物车,带每一行的小计,从大到小排列。
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}
]JSON 数组就是原样的列表。q:compute 给每条记录添加一个字段;{price} 和 {qty} 是记录自己的字段。
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