Wikis & learning

Design a small JSON response for live search

A search endpoint can accept a short term and return a list of matches. Keeping its response shape consistent allows the browser to show empty results without a separate parsing rule.

A search endpoint can accept a short term and return a list of matches. Keeping its response shape consistent allows the browser to show empty results without a separate parsing rule.

Walkthrough

The example filters a small in-memory index, turns the retained values back into a list and encodes the response. In an HTTP handler set the response content type to application/json before sending the body.

PHP example

<?php
$term = 'map';
$titles = ['Guidebook', 'Map editor', 'Map tiles'];
$items = array_values(array_filter($titles, fn(string $t): bool => stripos($t, $term) !== false));
echo json_encode(['items' => $items, 'count' => count($items)], JSON_THROW_ON_ERROR);

Expected output

{"items":["Map editor","Map tiles"],"count":2}

Change and check

Try an unmatched term. Check that the items property is still an empty JSON list. In a client interface, discard older results when a newer query has already completed.