Reject Non-Finite Numbers Before Exporting a Stock Summary as JSON
A floating-point calculation can produce NaN or infinity. Python's JSON encoder permits these tokens by default, even though they are outside the JSON number grammar. An export boundary can reject them rather than send an ambiguous summary to another system.
This global dropshipping example uses synthetic warehousing and fulfillment totals. It writes a string in memory, with no production update or customer record.
import json
import math
def encode_summary(value):
return json.dumps({'total': value}, allow_nan=False)
assert json.loads(encode_summary(0)) == {'total': 0}
assert json.loads(encode_summary(2.5)) == {'total': 2.5}
assert json.loads(encode_summary(-1)) == {'total': -1}
for invalid in [math.nan, math.inf, -math.inf]:
try:
encode_summary(invalid)
except ValueError:
pass
else:
raise AssertionError('non-finite number accepted')
assert json.loads(encode_summary(None)) == {'total': None}
print('7 checks passed')
The json encoder documentation describes allow_nan=False and the resulting ValueError for non-finite floats. Seven executed checks cover zero, a finite fraction, a negative number, all three non-finite forms and None.
The negative number and None intentionally pass serialization. This boundary checks JSON encoding, not a stock schema. If the field must be a non-negative integer, add that separate rule before encoding. Likewise, a finite float is not necessarily an exact monetary or weight value.
If a write to a file or network follows this step, retain the validated string before sending it. This example does not demonstrate atomic file replacement, delivery retries, receiver validation or a running warehouse connector.

Computer workstations and printing equipment in a warehouse.
All rights reserved