Japanese Postal Code Auto-Fill Without an API13 min read2,529 words

Japanese Postal Code Auto-Fill Without an API

Build Japanese postal-code auto-fill with Japan Post’s free CSV data. Learn to clean, split and serve it, then handle ambiguous codes without an API key.

Japanese postal code auto-fillJapan Post postal code dataJapanese address formpostal code lookup JavaScriptJapanese checkout UX
Japanese Postal Code Auto-Fill Without an API

Build Japanese Postal-Code Auto-Fill Without an API

A Japanese checkout that asks customers to type their prefecture, city and town after they've entered a postal code creates avoidable work. People expect those address fields to fill automatically. When they don't, the form feels clunky - and that friction can cost you completed orders.

You don't need a paid lookup service or a third-party script running on your checkout page. Japan Post publishes postal-code data you can process into small static JSON files, then look up in the browser. The trade-off is that you own the build/update steps, and you'll need to handle a few quirks in the source data.

This guide covers the data file, the fields and exceptions that matter, a practical CSV-to-JSON build, and front-end behavior that doesn't fight the user. It also covers ambiguous postal codes, missing records, and monthly maintenance - the stuff that turns a quick demo into something you can actually ship.

Which Japan Post data file should you use?

Japan Post publishes postal-code data for download. If you're starting fresh, use the newer UTF-8 file, utf_ken_all.zip, instead of the older KEN_ALL.CSV. Japan Post has offered the newer file since its June 2023 update, and it's generally easier to work with for a web build.

There are three practical differences. First, the newer file uses UTF-8, so you can process Japanese text without an extra Shift_JIS conversion step. Second, it represents each postal code on a single record. In the older file, some long town names are split across multiple records, which means your importer needs logic to stitch them back together. Third, the newer data uses full-width katakana for readings, which can be handy if your form also supports address readings.

Map only the fields the form needs

The file has 15 columns, but you don't need them all for a basic address auto-fill. For the sample row below, the postal code is 1000001, followed by the prefecture, city (or ward), and town:

13101,"100","1000001","トウキョウト","チヨダク","チヨダ","東京都","千代田区","千代田",0,0,0,0,0,0

The relevant zero-based indexes in JavaScript are:

CSV column JavaScript index Field Example
3 2 Postal code 1000001
7 6 Prefecture 東京都
8 7 City or ward 千代田区
9 8 Town 千代田

Columns 4-6 contain readings in katakana. Column 13 (JavaScript index 12) is a flag associated with postal codes that cover multiple towns. You don't have to use that flag just to build the lookup, but you do need to support multiple results for a code instead of assuming every code maps to exactly one town.

Preserve postal codes as strings

Postal codes are identifiers, not numbers. A code like 0600042 will lose its leading zero if an editor or script treats it as a number, and then your lookup breaks. Keep postal codes as strings from the CSV through to the JSON key and the browser input.

Japan Post says in its readme that it doesn't claim copyright on the postal-code data and that it may be freely distributed. Still, read the current readme and terms yourself before shipping the data in a commercial product - don't rely on a recap.

How do you turn the CSV into usable lookup data?

The source contains more than 100,000 records. Sending the whole dataset to every checkout visitor isn't necessary. For a checkout flow, the browser really only needs one postal-code result at a time.

Split the records into static JSON files based on the first three digits of each code. A lookup for 1000001 can request /zip/100.json, then find the full code inside that smaller file.

Each postal code should map to a list of address entries, not just one entry. This matters because one postal code can cover more than one town. If you keep the data structure honest during the build, you're less likely to end up with the front end quietly guessing the wrong town later.

Clean special town values before publishing

The town column isn't always a value you should paste into a customer's address. Japan Post uses special descriptions, including 以下に掲載がない場合 ("not listed below), ○○の次に番地がくる場合 (the block number follows the city name), and values ending in 一円 (the whole municipality). Those are data labels, not actual town names.

Some town values also include a note in full-width parentheses describing the block range covered by a postal code. For example, 大通西(1~19丁目) includes a range note. The customer still needs to enter their own block number, so you should keep only the part before the parenthesis.

const cleanTown = (town) => {

if (town === '以下に掲載がない場合') return '';

if (/の次に番地がくる場合$/.test(town)) return '';

if (/一円$/.test(town)) return '';

return town.replace(/(.*$/, '');

};

Build prefix-based JSON files

Below is a Node.js example that keeps the postal code as a string, cleans town names, and stores a list of unique results for each code. It uses a simple comma split because the relevant Japan Post fields don't contain ASCII commas in the expected format. If you want to be resilient to format changes, switch to a CSV parser and validate the expected number of columns instead of relying on that assumption.

// Usage: node build-zip.mjs utf_ken_all.csv public/zip

import { readFileSync, mkdirSync, writeFileSync } from 'node:fs';

import { join } from 'node:path';

const [, , csvPath, outDir] = process.argv;

const cleanTown = (town) => {

if (town === '以下に掲載がない場合') return '';

if (/の次に番地がくる場合$/.test(town)) return '';

if (/一円$/.test(town)) return '';

return town.replace(/(.*$/, '');

};

const parseLine = (line) =>

line.split(',').map((field) => field.replace(/^"|"$/g, ''));

const files = {};

for (const line of readFileSync(csvPath, 'utf8').split(/\r?\n/)) {

if (!line) continue;

const columns = parseLine(line);

const zip = columns[2];

if (!/^\d{7}$/.test(zip)) continue;

const entry = [columns[6], columns[7], cleanTown(columns[8])];

const bucket = (files[zip.slice(0, 3)] ??= {});

const entries = (bucket[zip] ??= []);

if (!entries.some((existing) => existing.join() === entry.join())) {

entries.push(entry);

}

}

mkdirSync(outDir, { recursive: true });

for (const [prefix, data] of Object.entries(files)) {

writeFileSync(join(outDir, `${prefix}.json`), JSON.stringify(data));

}

console.log(`${Object.keys(files).length} files written to ${outDir}`);

The generated structure looks like this:

{

"1000001": [["東京都", "千代田区", "千代田"]]

}

These prefix files are static assets. You don't need a lookup server, API key, or any runtime dependency. The browser fetches only the relevant prefix file, and ordinary static hosting or a CDN can serve it. For production, add build checks for malformed rows, missing output, and unexpected changes in record counts. A build that quietly emits incomplete data is worse than a build that fails loudly.

How should the form handle postal-code lookups?

The lookup is only one part of the form. Use meaningful field names and browser autocomplete attributes so customers still benefit from their browser's address helpers.

A typical Japanese checkout includes a postal-code field, prefecture, city/ward, town, block number, and building/room number:

<label>Postal code <input name="postal_code" autocomplete="postal-code"

inputmode="numeric" placeholder="123-4567"></label>

<label>Prefecture <select name="prefecture" autocomplete="address-level1">

<option value="">Select a prefecture</option>

<option>Hokkaido</option>

</select></label>

<label>City or ward <input name="city" autocomplete="address-level2"></label>

<label>Town <input name="town"></label>

<label>Block number <input name="address_line1" autocomplete="address-line1"></label>

<label>Building and room number <input name="address_line2" autocomplete="address-line2"></label>

In a Japanese checkout, the prefecture options should be in Japanese (for example, 東京都) and include all 47 prefectures. Some forms combine town and block number into one field. Either approach can work - just pick one and keep it consistent in validation, storage, and order exports.

Normalize input and load only what is needed

Japanese users may type full-width digits, hyphens, or the postal mark 〒. Normalize before checking length. Unicode NFKC converts full-width digits and punctuation to compatible forms. After that, stripping non-digits should leave the seven-digit code.

const form = document.querySelector('form');

const cache = {};

const normalizeZip = (value) =>

value.normalize('NFKC').replace(/[^0-9]/g, '');

async function lookup(zip) {

const prefix = zip.slice(0, 3);

cache[prefix] ??= fetch(`/zip/${prefix}.json`)

.then((response) => (response.ok ? response.json() : {}));

return (await cache[prefix])[zip] ?? [];

}

The cache prevents refetching the same prefix file as the user edits the postal code. If a request fails, you need to decide how graceful you want to be. This example returns no results and leaves the fields alone, which allows manual entry. You'll also want to log failures outside the customer-facing flow so broken asset paths don't go unnoticed.

Respect edits and avoid false certainty

Auto-fill should reduce typing, not take over the address. Keep track of which fields the customer has edited, and don't overwrite them once a lookup completes. This also covers a timing issue: the network response may arrive after the customer has started correcting a suggested value.

If a postal code returns multiple towns, fill only the prefecture and city, then let the user choose or type the town. Don't just pick the first record because it appears first in the file. And if the code is unknown, do nothing. Japan Post maintains separate data for some large businesses and post-office boxes, so a postal code may be valid but still not appear in your particular dataset.

const edited = new Set();

for (const name of ['prefecture', 'city', 'town']) {

form.elements[name].addEventListener('input', () => edited.add(name));

}

async function fillAddress() {

const zip = normalizeZip(form.elements.postal_code.value);

if (zip.length !== 7) return;

const hits = await lookup(zip);

if (hits.length === 0) return;

const [prefecture, city, town] = hits[0];

const setIfUntouched = (name, value) => {

if (!edited.has(name)) form.elements[name].value = value;

};

setIfUntouched('prefecture', prefecture);

setIfUntouched('city', city);

setIfUntouched('town', hits.length === 1 ? town : '');

form.elements.address_line1.focus();

}

form.elements.postal_code.addEventListener('input', fillAddress);

If the form needs to live longer (or users can change their minds), consider distinguishing "the user edited this field" from "the user cleared this field." The simple Set above preserves both actions, which is usually safer than repopulating a field the user deliberately emptied. If the user changes the postal code and expects fresh suggestions, give them a clear way to reset or rerun suggestions rather than silently overriding their edits.

How do you maintain the lookup without adding operational risk?

Postal-code data changes over time due to corrections, new developments, and municipal updates. Japan Post publishes monthly updates, including add and delete files. The simplest operational choice is to download the current utf_ken_all.zip and rebuild the full set of JSON files once a month. You can automate the download and build with a scheduled CI job, but you should still make the pipeline fail loudly if the source file is missing or the output ends up unexpectedly empty.

You can do incremental processing using monthly add/delete files, but it adds state: you have to apply changes in the right order and ensure deletions remove the correct records. For most checkout implementations, a monthly full rebuild is a better trade-off. The dataset is small enough to process offline, and rebuilding from a complete source is easier to reason about than maintaining a patch chain.

Add checks around the data pipeline

Treat this like a small data pipeline, not a one-off script. At minimum, verify that each postal code has seven digits, required address columns are present, and output files are actually written. Track the number of input rows and generated codes - if the count drops massively, investigate before deploying.

Keep a previous known-good build around. If Japan Post changes the source format (or the build fails), your checkout should continue serving the last valid lookup rather than shipping empty files. A postal-code lookup is an enhancement; your customers still need a working checkout when it's down.

Before release, check these behaviors:

  • Postal codes keep leading zeros.
  • Full-width digits, hyphens, and 〒 normalize correctly.
  • Special town descriptions and parenthetical range notes are cleaned.
  • Codes that map to multiple towns don't trigger a guessed town value.
  • Unknown codes and failed requests leave manual entry available.
  • A customer's edits aren't overwritten by a late lookup.
  • The data rebuilds and gets reviewed on a regular schedule.

The bigger trade-off is ownership. Using free, local data avoids API costs, third-party availability risk, and checkout-time network dependencies beyond your own static assets. In exchange, your team owns the update process and data validation. That's usually a sensible swap for a stable reference dataset - as long as the maintenance job has a real owner and the form stays usable when lookups fail.

Conclusion

Japanese postal-code auto-fill is a small change with a noticeable impact on checkout quality. Use Japan Post's UTF-8 data, keep codes as strings, clean special town labels, and split the output so visitors fetch only a small static file.

The front end matters just as much as the data: normalize full-width input, avoid guessing when a code covers multiple towns, preserve customer edits, and keep manual entry available when a lookup fails. With a monthly rebuild and a few validation checks, you can match the expected local behavior without paying for a runtime API or making checkout dependent on a third party.

Frequently Asked Questions

No. Japan Post publishes postal-code data that you can process into static JSON files and serve from your own site. The browser can look up the code locally after loading a small prefix file. Review the data readme and keep your generated files current.
The source has more than 100,000 records, while a checkout needs only one result. Splitting JSON by the first three postal-code digits reduces the amount each visitor downloads and lets you serve the lookup as static files.
Fill the prefecture and city, but do not guess the town. Leave it for the customer to enter or show the available towns as choices. Selecting the first record can produce a plausible-looking but incorrect address.
No. Some valid codes may be absent from this dataset, including codes handled through separate Japan Post files. If there is no match or the lookup fails, leave the fields editable and allow manual entry.
Japan Post publishes updates monthly, so a monthly full download and rebuild is a practical default. Keep the last known-good files available if an update fails; use incremental updates only if their extra operational complexity is worthwhile.

Related articles