Ao Tanaka scored the winning goal from close range early in the second half. It took about two minutes for video review officials to confirm the ball hadn’t gone out of bounds before the goal that gave Japan the win at Khalifa International Stadium, which is where Japan had shocked Germany in its opener.
Japan finished at the top of Group E to set up a last-16 matchup against Croatia. Spain finished second and will take on Morocco.
Spain and Germany — which beat Costa Rica 4-2 — both had four points in the group. But Spain had a superior goal difference from its first group match so Germany was eliminated.
The group standings bounced back and forth during both matches. Costa Rica was beating Germany at one point. If that result had stood, Costa Rica would have eliminated Spain.
Álvaro Morata scored first for Spain in the 11th minute and Spain was in control until Japan rallied after halftime. Ritsu Doan equalised in the 48th with a left-footed shot from outside the box, and Tanaka added the second three minutes later.
Morata became the first player to score in the first three Spain matches at the World Cup since Telmo Zarra in 1950.
Spain had opened with a 7-0 rout of Costa Rica before conceding late in a 1-1 draw against Germany.
Japan was eliminated by Belgium in the last 16 in Russia. They have never gone past the round of 16 at World Cups.