The Danes, who replied in the 81st when Jon Dahl Tomasson tapped in the rebound from his own penalty kick, failed to advance from the group stage for the first time in four World Cup appearances. Shinji Okazaki scored an insurance goal in the 87th minute for the Japanese.
Japan's first two goals came from free kicks less than 15 minutes apart, as it collected its second win in Group E. The Japanese finished with six points compared to three for third-place Denmark. Cameroon was last in the group.
The Japanese have now reached the knockout round for the second time. They also advanced in 2002 when they were tournament co-hosts. Japan will face Paraguay in Pretoria on Tuesday in the second round.