File size: 4,425 Bytes
c3a45c0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 | ---
# SPDX-License-Identifier: CC-BY-4.0
# Copyright (c) 2026 Martin Schröder <info@swedishembedded.com>
title: Writing a JSON answer file with a script
tiers: rule 1, procedure 2, example 3, mistakes 2
---
# Writing a JSON answer file with a script
For tasks that ask for `answer.json` or any other structured answer file.
<!-- tier: 1 -->
## Rule
**The task's own files and stated rules always win over this page; use this page only for what
the task leaves open.**
1. **The shape in the request is exact.** Same key names, same nesting, same value types. Add no
key, drop no key, rename no key.
2. **A label must be one the request lists**, spelled as the request spells it.
3. **"Nothing" has three spellings that are not interchangeable:** an empty list `[]`, the JSON
value `null` without quotes, or a word the request gives. Use the one the request states for
that field.
4. **The file holds the answer only:** no explanation, no reasoning, no markup, no code fence.
5. **Let a script write the file with a JSON library.** Then it is always valid JSON.
6. **A program goes into a script file, not into a quoted command line.**
<!-- tier: 2 -->
## Procedure
1. Copy the example shape from the request into your notes. Mark for each field: its type
(number, text, list, object, null allowed?) and its allowed values.
2. Write the program to a file with the file-writing tool, as plain text.
3. In the program: read the inputs, compute, **print** the intermediate values, build the answer
as a dictionary in the request's shape, write it with the JSON library.
4. Run it with one short command. If it fails, read the last line of the error, fix that line in
the file, run again. If it failed three times, make it smaller: one result at a time.
5. Money as a JSON number: convert the exact decimal at the very end. Money as text with two
decimals: format it with two decimals. Follow the request.
6. Read the answer file back with a one-line parse. Compare its keys with the request's shape.
7. Delete the program file.
<!-- tier: 3 -->
## Worked example
Illustration only, with invented data. Your task's data differs: take no fact, count or
expected result from this example.
Invented request: write `answer.json` as
```json
{"status": "ok", "late_items": ["X0"], "fee": 0.0, "waiver": null}
```
with `status` one of `ok` or `blocked`, `late_items` empty if none, `waiver` `null` if none.
Program file `calc.py`:
```python
import csv
import json
from decimal import ROUND_HALF_UP, Decimal
rows = list(csv.DictReader(open("items.csv")))
late = [r["id"] for r in rows if r["state"] == "late"]
fee = sum(Decimal(r["fee"]) for r in rows if r["state"] == "late")
fee = fee.quantize(Decimal("0.01"), ROUND_HALF_UP)
print("rows", len(rows), "late", late, "fee", fee)
answer = {"status": "ok", "late_items": late, "fee": float(fee), "waiver": None}
json.dump(answer, open("answer.json", "w"), indent=1)
```
Run `python3 calc.py`, then check:
`python3 -c "import json; print(json.load(open('answer.json')))"`.
The library writes Python `None` as JSON `null` and an empty list as `[]`.
Wrong versions of the same answer and why they fail:
| Written | Problem |
|---|---|
| `"late_items": null` | the request said an empty list |
| `"waiver": "null"` | a four-letter text, not the JSON value |
| `"fee": "12.50"` | text where the shape shows a number |
| `"status": "OK"` | not spelled as the request lists it |
| `{'status': 'ok'}` | single quotes are not JSON |
| an added `"note"` key | the shape has no such key |
| `{"late": [...]}` | a renamed key |
| a bare list where the shape shows an object with a list inside | the wrapper key is missing |
<!-- tier: 2 -->
## Common mistakes
- Writing the file with a shell echo and losing or mixing the quotes.
- Dropping the outer wrapper key and writing only its content.
- Returning an object keyed by id where the shape shows a list of objects, or the reverse.
- Giving a date where an amount was asked, or an amount where a date was asked.
- Leaving out a line for an item the request said to list ("one line per invoice").
- Reporting totals that are not the sum of the lines written in the same file.
- Writing a correct file, then rewriting it again and again. Parse it once; if it matches the
shape, stop.
- Believing a write failed because the tool's confirmation looked unusual. Read the file back
instead of writing it again.
|