Recent chats
ASKGEEZ Q&A GUIDETechnology & devices

How can I sort a JSON list of records by a chosen field?

Quick answer

Load the JSON array, confirm every item is a record and the chosen field exists with the expected type, then sort with a key function that explicitly treats the field as text or a number. The example sorts numeric score values and rejects missing or nonnumeric values. Save the sorted list to a different file, reload it, and verify the order. In JSON output, sort_keys=True sorts object keys, not the records in the array. [S1]

LET’S WORK THROUGH IT

The question, the details, the next step.

Question

I have a JSON array of records. What is the basic way to sort it by one field and keep the original file untouched?

Geez

In Python, a JSON array becomes a list, and each JSON object becomes a dictionary. You can sort that list with a key function, then write the result to another file with json.dump. [S1]

Here is a complete example. It creates a small input file, sorts by numeric score in ascending order, and writes records-sorted.json separately:

import json

records = [
    {"name": "Mina", "score": 12},
    {"name": "Omar", "score": 5},
    {"name": "Lee", "score": 9},
]

with open("records.json", "w", encoding="utf-8") as f:
    json.dump(records, f, indent=2)

with open("records.json", encoding="utf-8") as f:
    data = json.load(f)

field = "score"

if not isinstance(data, list):
    raise ValueError("Expected a JSON array")

for index, record in enumerate(data):
    if not isinstance(record, dict):
        raise ValueError(f"Record {index} is not an object")
    if field not in record:
        raise ValueError(f"Record {index} is missing {field!r}")
    value = record[field]
    if isinstance(value, bool) or not isinstance(value, (int, float)):
        raise ValueError(f"Record {index} has a nonnumeric {field!r}")

sorted_records = sorted(data, key=lambda record: record[field])

with open("records-sorted.json", "w", encoding="utf-8") as f:
    json.dump(sorted_records, f, indent=2)

with open("records-sorted.json", encoding="utf-8") as f:
    saved = json.load(f)

assert [record[field] for record in saved] == [5, 9, 12]
print("Verified sorted output")

The validation makes the policy explicit: a missing field or a value that is not a number stops the run instead of silently choosing an order.

Follow-up question

What if the chosen field is a name or another text value instead of a number?

Geez

Choose text ordering deliberately, and validate that every record has a string for the field. For example, replace the numeric check and sort line with:

if not isinstance(value, str):
    raise ValueError(f"Record {index} has a non-text {field!r}")

sorted_records = sorted(data, key=lambda record: record[field])

This makes the field type explicit. If you need particular rules for case, accents, or language-specific ordering, define those rules rather than assuming the default matches your needs.

Follow-up question

Should I put records with missing keys at the end instead of stopping?

Geez

Either policy can be reasonable, but choose it explicitly. Stopping with an error is useful when every record is supposed to have the field, because it exposes malformed input. If missing values are expected, one simple policy is to separate records that have the field from those that do not, sort the first group, and append the missing group. Validate the present values’ types before sorting; do not mix missing values, numbers, and text in one comparison key and rely on accidental ordering. [S1]

Follow-up question

How do I confirm I sorted the records, not just the keys inside each record?

Geez

Reload the output file and inspect the chosen field in sequence, as the example’s assertion does. That checks the saved file rather than only the in-memory list. Also, sort_keys=True in json.dump sorts dictionary keys when serializing; it does not reorder the list of records. [S1] For a different expected order, change the assertion to match your chosen field and direction. For descending numeric order, use reverse=True in the sorted call and update the verification sequence.

A practical checklist

  • Set the sort field and decide whether it must be text or numeric.

  • Check that the top-level JSON value is a list and each item is an object.

  • Choose whether missing fields should stop processing or follow a documented placement rule.

  • Validate present values before sorting; reject mixed or unexpected types.

  • Write to a separate output file, reload it, and verify the field sequence.

A few more useful answers

Does `sort_keys=True` sort my records?

No. It orders keys inside serialized objects; sort the list itself with sorted(..., key=...). [S1]

How should I decide how text values sort?

Choose the comparison rules you need, such as how case or accents should be handled, and apply them consistently rather than assuming the default matches your needs.

Sources

References used for this guide.

  1. [S1] Python 3.15 json reference: JSON arrays map to lists and objects to dictionaries
    docs.python.org · Checked

YOUR QUESTION. YOUR DETAILS.

Let’s work through your situation.

Get a tailored answer or help with your next task. Starts at $1, with a quote before you pay.

Ask your own question
← Back to Geez at Work