The Warlock may have an Artifact
On page 219 of the DMG, there is a Major Beneficial Property on the Artifact table that allows the artifact's possessor to cast a sixth level spell. (Entry roll 71-80). There are no class restrictions on the spell stated in that description. The property includes chances for being able to cast a 4th, 5th, 6th or 7th level spell. It is a fairly powerful feature, since that spell may end up being cast more than once ...
Once cast, roll on a d6; on a 1-5 the spell cannot be cast again until the next dawn. (DMG, p. 219)
A level 20 character having an artifact is not beyond the limits of the game.
Beyond that, the DM can provide that spell because the DM in D&D 5e is master of rules. (DMG, p. 5; also the topic of Part III of the DMG). While none of the warlock NPC characters in Volo's Guide to Monsters are shown as having that spell, the DM can include that spell for any caster who could cast 6th level (or above) spells. Two other answers address this point as well.
Modifying a Class Spell list is addressed in the DMG
Changing Spell Lists (DMG, p 287) addresses this case directly.
Modifying a class's spell list usually has little effect on the
character's power but can change the flavor of a class significantly.
... you could build a new paladin spell list with spells meant to
protect their masters, drawn from the sorcerer or wizard lists. Be cautious when changing the warlock's spell list. Since warlocks regain their spell slots after a short rest, they have the potential to use certain spells more times in a day than other classes.
Given that magic jar is a 6th level spell, the limitation imposed by mystic arcanum (cast once per day; PHB, p. 108) would be a sensible choice by the DM in this case.
While the NPC spell casters typically remain within the same spell list as a given class (p. 342, MM) even when spell swapping is decided, the customization of an NPC to include spells from other lists is similar to how a bard can use spells from other lists via Magic Secrets, how a Cleric's Domain spells often come from other spell lists, or how a Warlock's Pact of the Tome ability provides (ritual) spells from other classes. It's not a huge reach to customize an NPC with spells from another spell list. The Changing Spell Lists section (DMG, p. 287) addresses this directly.