Brightlane's product detail API needs a single product returned as a structured JSON document.
Write a query to return a JSON object for product id = 7 containing the product's ID, name, and price under the keys 'id', 'name', and 'price'.
Assumptions:
- The
productstable has one row per product with anid, aname, and aprice. - Product
id = 7is on record. The output is a single row holding the assembled JSON document.
Output:
- A single row with one column,
product_doc, containing a JSON object with the keys'id','name', and'price'.
Schema · ecommerce 5 tables
Run previews · Check grades
Write a query, then run it to see results here.
Worked solution Try it yourself first
SELECT
JSON_BUILD_OBJECT('id', id, 'name', name, 'price', price) AS product_doc
FROM
products
WHERE
id = 7 The shape
json_build_object('id', id, 'name', name, 'price', price) packs the three columns of a single product row into a JSON object whose keys are the literal strings and whose values are the column values. The WHERE id = 7 restricts the input to that one product, so the function runs once and the query returns one row.
Clause by clause
SELECT json_build_object('id', id, 'name', name, 'price', price) AS product_doclists the keys and values in alternating order: key, value, key, value. PostgreSQL infers each value's JSON type from the column type, soidandpricecome out as JSON numbers andnamecomes out as a JSON string. The aliasproduct_docnames the single output column.FROM productsreads the product records.WHERE id = 7narrows the input to the one product withid = 7, which isCrest Airat price 1299. With only one row reachingSELECT, the function builds exactly one JSON object and the result set is the single row{ "id": 7, "name": "Crest Air", "price": 1299 }.
You practiced json_build_object('key1', value1, 'key2', value2, ...) — assemble a JSON object from alternating key-value arguments; PostgreSQL infers each value's JSON type.