JavaScript: Round-trip a quantity Map through JSON entries
Serializing an ordinary Map directly produces an empty JSON object, even when the Map has entries. For a small interchange format with string keys and integer quantities, export an array of key-value pairs and validate that format on import.
Set up
Tested on Debian 13 Linux with Node.js v24.19.0. Use Bash, Node.js on your PATH, a text editor, and the mktemp, rm and rmdir utilities. No packages or network access are needed. Keep the same terminal through cleanup. Stop if setup fails before saving the source.
start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1Run the example
Save as javascript-map-json-entry-array.mjs:
import assert from 'node:assert/strict';
function readQuantities(text) {
const entries = JSON.parse(text);
if (!Array.isArray(entries)) throw new TypeError('Expected an entry array');
const quantities = new Map();
for (const entry of entries) {
if (!Array.isArray(entry) || entry.length !== 2 ||
typeof entry[0] !== 'string' ||
!Number.isSafeInteger(entry[1]) || entry[1] < 0) {
throw new TypeError('Expected a string and a nonnegative safe integer');
}
if (quantities.has(entry[0])) throw new Error('Duplicate quantity key');
quantities.set(entry[0], entry[1]);
}
return quantities;
}
const original = new Map([['pens', 3], ['pads', 0]]);
assert.equal(JSON.stringify(original), '{}');
const text = JSON.stringify([...original]);
const restored = readQuantities(text);
assert.deepEqual(restored, original);
assert.deepEqual([...restored.keys()], ['pens', 'pads']);
assert.equal(readQuantities('[]').size, 0);
assert.throws(() => readQuantities('[["pens",1],["pens",2]]'), /Duplicate/);
for (const invalid of ['{}', '[["pens"]]', '[[1,2]]', '[["pens",-1]]', '[["pens",1.5]]']) {
assert.throws(() => readQuantities(invalid), TypeError);
}
assert.throws(() => readQuantities('['), SyntaxError);
console.log('Direct Map JSON:', JSON.stringify(original));
console.log('Entry-array JSON:', text);
console.log('Restored pens:', restored.get('pens'));
console.log('Order, empty input, duplicates, shape, and syntax checks: passed');Run:
node javascript-map-json-entry-array.mjsObserved output:
Direct Map JSON: {}
Entry-array JSON: [["pens",3],["pads",0]]
Restored pens: 3
Order, empty input, duplicates, shape, and syntax checks: passedMake the entry format explicit
The source Map has two entries, but its direct JSON result contains neither. Spreading the Map produces an array of pairs that JSON can represent. The importer reconstructs a Map; the test then checks that the original insertion order survives.
The JSON serialization algorithm does not automatically serialize a Map’s internal entries. This example exports them deliberately. It uses an array instead of converting keys to object properties, so the wire format explicitly represents an ordered sequence of pairs.
The export assumes the source Map already has string keys and nonnegative safe integers as values. The importer checks every pair before accepting it. If the source Map may hold other values, validate it before exporting too.
Reject duplicate keys before constructing the result
A Map can hold only one value per key. Passing repeated keys directly to its constructor would keep the later value. The importer checks for duplicates before insertion and rejects the document, so a repeated quantity cannot silently replace an earlier one.
The type checks reject a JSON object at the top level, incomplete pairs, numeric keys, negative values and fractions. Malformed JSON still raises a syntax error. Empty entry arrays are valid. The helper permits empty string keys and zero quantities; change those rules explicitly if your format requires otherwise.
This is a format for quantities, not a general Map serializer. Object identity, BigInts and arbitrary nested values need other representations and validation rules. Apply input-size limits before parsing large external documents, and version the format if its schema changes.
Clean up
Remove the saved file and empty scratch directory. If the directory is not empty, inspect its contents before removing anything else.
rm -- javascript-map-json-entry-array.mjs
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dirAcknowledgements
This post was created with assistance from AI.