MySQL
JSON
data conversion
SQL query
programming tutorial

How to convert result table to JSON array in MySQL

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

MySQL provides native JSON functions that let you return query results directly as JSON arrays. This is useful for APIs, reporting pipelines, and SQL-only integration layers where you want the database to produce structured payloads.

The core pattern is to build one JSON object per row and then aggregate all row objects into an array with JSON_ARRAYAGG. This article covers the common query patterns and caveats.

Core Sections

1. Build per-row JSON objects

sql
1SELECT JSON_OBJECT(
2  'id', id,
3  'name', name,
4  'email', email
5) AS row_json
6FROM users;

JSON_OBJECT maps columns to keys and creates one JSON object per row.

2. Aggregate rows into one JSON array

sql
1SELECT JSON_ARRAYAGG(
2  JSON_OBJECT('id', id, 'name', name, 'email', email)
3) AS users_json
4FROM users;

This returns a single row containing an array of user objects.

3. Add ordering and filtering

sql
1SELECT JSON_ARRAYAGG(
2  JSON_OBJECT('id', id, 'name', name, 'createdAt', created_at)
3) AS active_users
4FROM (
5  SELECT id, name, created_at
6  FROM users
7  WHERE status = 'ACTIVE'
8  ORDER BY created_at DESC
9  LIMIT 100
10) t;

Use a subquery when you need deterministic ordering and pagination before aggregation.

4. Handle null and empty result sets

If no rows match, JSON_ARRAYAGG returns NULL. Convert that to empty array when required by clients.

sql
1SELECT COALESCE(
2  JSON_ARRAYAGG(JSON_OBJECT('id', id, 'name', name)),
3  JSON_ARRAY()
4) AS result
5FROM users
6WHERE status = 'UNKNOWN';

This keeps API contracts stable.

5. Build a repeatable validation checklist

Once the implementation is in place, create a deterministic validation checklist for MySQL result-to-JSON conversion. At minimum, include one baseline scenario, one edge-case scenario, and one failure-path scenario with expected outcomes documented in plain language. This prevents knowledge from staying implicit and reduces the risk of regressions during dependency updates or refactors.

A useful checklist also captures runtime assumptions: framework versions, SDK versions, configuration flags, and environment variables required for a successful run. Many teams skip this because the setup seems obvious during initial development, but those hidden assumptions are usually what break first when code moves to CI, staging, or another developer machine.

text
1validation checklist
2- baseline case with expected output and key fields
3- edge case with constrained or unusual input
4- failure case with expected error handling behavior
5- recorded runtime and dependency assumptions

Keep this checklist versioned with code. If behavior changes, update the expected outputs in the same pull request so future debugging has an authoritative reference for what changed and why.

6. Operational hardening and maintenance

Long-term reliability for MySQL result-to-JSON conversion requires observability and explicit ownership. Add targeted logs and metrics around critical steps so incident responders can quickly identify whether failures come from input quality, environment drift, external service dependencies, or code regressions. Without these signals, most incident time is lost reconstructing context instead of fixing root causes.

Define maintenance routines for upgrades and compatibility checks. Libraries and platforms evolve continuously, and subtle behavior changes are common. Lightweight smoke tests should run regularly, not only during feature work, to catch drift before it reaches production.

bash
# example recurring check command
make smoke-test

Finally, document rollback criteria in advance. If a deployment changes MySQL result-to-JSON conversion behavior unexpectedly, teams should know when to roll back immediately versus when to hot-fix forward. This converts operational response from guesswork into a controlled process and improves overall system resilience.

Common Pitfalls

  • Forgetting to wrap ordered datasets in subqueries before JSON aggregation.
  • Returning NULL instead of empty arrays for no-match cases.
  • Over-aggregating massive datasets and creating oversized JSON payloads.
  • Assuming JSON key order has semantic meaning for downstream consumers.
  • Mixing incompatible data types without explicit casting in JSON objects.

Summary

Converting MySQL result tables to JSON arrays is straightforward with JSON_OBJECT plus JSON_ARRAYAGG. For production use, make ordering explicit, normalize empty-result behavior, and control payload size with filtering and limits. Done correctly, MySQL can serve clean JSON responses without extra application-side reshaping.


Course illustration
Course illustration

All Rights Reserved.