brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: a JSON.parse reviver turns date strings back into real Date objects

Json
~/tips/tip-json-parse-reviver-dates

const text = '{"createdAt":"2026-11-30T09:00:00Z","name":"x"}';

Convert dates once while parsing instead of all over your code.

JSON has no date type, so a date goes out as a Date and comes back as a string. Then some line calls getTime on it and falls over.

JSON.parse takes a second argument that sees every key and value:

const text = '{"createdAt":"2026-11-30T09:00:00Z","name":"x"}';

const data = JSON.parse(text, (key, value) =>
  key.endsWith('At') && typeof value === 'string'
    ? new Date(value)
    : value
);

console.log(data.createdAt.getFullYear());

Whatever the function returns replaces the value. Here every key ending in At becomes a Date, at any depth, and the rest passes through untouched.

Always return value for things you do not change. Forget it and the property is removed, which is the classic mistake with revivers: you end up with undefined as the whole result.

I decide by key name on purpose. Guessing from the content would also convert a product code or a title that happens to look like a date. A string that cannot be parsed becomes an invalid date without throwing, so check input you do not control.

Further reading: MDN: JSON.parse()

More Json tips echo '{"id":1,"payload":"{\"user\":\"ann\",\"tags\":[\"x\",\"y\"]}"}' | jq -c '.payload | fromjson | .tags' jq empty config.json Paths() tells you where in a big JSON document a value lives jq -c --slurpfile u users.json ' jq -cn --stream 'fromstream(1|truncate_stream(inputs))' big.json All Json tips (9) All topics

Link