Files and data
Restore known date fields after parsing JSON
Dates normally serialize as ISO strings in JSON. Restore a Date only for fields whose schema defines a timestamp, and validate the resulting date before using it.
Worked example
Node.js example · save as example.mjs and run node example.mjs
const json = JSON.stringify({createdAt: new Date("2026-01-01T00:00:00Z")});
const row = JSON.parse(json);
const createdAt = new Date(row.createdAt);
if (Number.isNaN(createdAt.getTime())) throw new Error("Invalid timestamp");
console.log(typeof row.createdAt);
console.log(createdAt.toISOString());How it works
Parsing JSON does not remember that a string came from a Date object. The conversion happens deliberately at the known createdAt field. This avoids converting arbitrary text that merely resembles a date into a different data type.
Limits and mistakes
Date-only fields and local appointment times may need different handling from UTC instants. Do not apply a broad date-detection regular expression to every string. Validate your required timestamp grammar as well as Date validity when accepting external input.
Check the result
Expect string and 2026-01-01T00:00:00.000Z. Check an invalid timestamp and an ordinary text field that looks like a date but should remain text.
Sources
Reference documentation for the behavior used in this guide: