Ir al contenido

Leer un archivo JSON ​

Traducción automática

Esta página se tradujo automáticamente del inglés y todavía no la revisó un hablante nativo; las correcciones son bienvenidas en GitHub. Si algo no coincide, vale el original en inglés.

Tarea: mostrar un carrito a partir de un archivo JSON, con el subtotal de cada línea, del mayor al menor.

yaml
# Recipe: read a JSON file and add a computed field to each record.
paths:
  components: ./components
json
[
  {"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}
]

Un array JSON es la lista tal como está. q:compute agrega un campo a cada registro; {price} y {qty} son los propios campos del registro.

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

Ver DATA-1 y DATA-3.

Licencia MIT · Hecho con VitePress