Japanese Postal Code to Address Auto-Fill, Built From Japan Post's Free Data (No API Key)
本文为原文前 6,000 字符的节选翻译,完整内容请查看原文。
Japanese Postal Code to Address Auto-Fill, Built From Japan Post’s Free Data (No API Key)
在日本,地址表单通常以邮政编码(郵便番号)开头。用户输入 7 位数字后,都道府县、市和町名会自动填充。如果表单没有此功能,日本用户会立刻察觉——这是结账页面“并非为日本设计”的最明显标志之一。我是一名日本本土开发者,曾多次为日本在线商店构建结账插件,因此我编写过不止一次此功能。你不需要付费 API 或在结账页面使用第三方脚本。日本邮政免费发布了相关数据,通过一个简单的构建步骤即可将其转换为静态 JSON 文件。本文将介绍数据来源、其特性、构建脚本以及前端代码。(关于日本结账表单的其他部分——如姓名顺序、假名、含税价格等,请参阅我之前的文章:《如何构建适用于日本的结账表单》。)
1. The data: one CSV from Japan Post
Japan Post publishes the postal code data on its download page. Use the newer UTF-8, one-record-per-line file, utf_ken_all.zip (about 2 MB zipped). It has been published since the June 2023 update. Why the newer file: It’s UTF-8. The classic KEN_ALL.CSV is Shift_JIS. Each postal code is one line. In the classic file, long town names are split across several records, which you have to stitch back together. Readings are full-width katakana (the classic file uses half-width). About using it: Japan Post’s readme says it does not claim copyright on the postal code data and that it may be freely distributed. Still, read the readme yourself before you ship. The data is updated monthly, with add/delete diff files each month. More on updating at the end.
1. 数据:来自日本邮政的一份 CSV 文件
日本邮政在其下载页面发布了邮政编码数据。请使用较新的 UTF-8 编码、每行一条记录的文件 utf_ken_all.zip(压缩后约 2 MB)。该文件自 2023 年 6 月更新以来开始发布。为什么要用新文件:它是 UTF-8 编码的。经典的 KEN_ALL.CSV 使用的是 Shift_JIS 编码。在新文件中,每个邮政编码占一行。而在经典文件中,较长的町名会被拆分到多条记录中,你需要手动拼接。读音部分为全角片假名(经典文件使用半角)。关于使用:日本邮政的自述文件(readme)声明不对邮政编码数据主张版权,且可以自由分发。不过,在发布产品前,请务必亲自阅读该自述文件。数据每月更新,并提供每月的增删差异文件。关于更新的更多信息见文末。
2. The columns you need
Each line has 15 columns. A row looks roughly like this: 13101,“100”,“1000001”,“トウキョウト”,“チヨダク”,“チヨダ”,“東京都”,“千代田区”,“千代田”,0,0,0,0,0,0 For auto-fill you only need four of them: # Column Example 3 Postal code (7 digits) 1000001 7 Prefecture 東京都 8 City / ward 千代田区 9 Town 千代田 Columns 4–6 are the readings in katakana (handy if you also want furigana for addresses). Column 13 is a flag that means one postal code covers two or more towns — keep that case in mind, it comes back in section 5. One more thing: open this file in Excel and the postal codes lose their leading zeros (0600042 becomes 600042). Always treat them as strings.
2. 你需要的列
每一行包含 15 列。一行数据大致如下:13101,“100”,“1000001”,“トウキョウト”,“チヨダク”,“チヨダ”,“東京都”,“千代田区”,“千代田”,0,0,0,0,0,0。对于自动填充,你只需要其中四列:第 3 列为邮政编码(7 位数字,如 1000001),第 7 列为都道府县(如 東京都),第 8 列为市/区(如 千代田区),第 9 列为町名(如 千代田)。第 4-6 列是片假名读音(如果你还需要地址的假名注音,这很有用)。第 13 列是一个标志,表示一个邮政编码覆盖了两个或多个町——请记住这种情况,第 5 节会再次提到。还有一点:在 Excel 中打开此文件时,邮政编码会丢失前导零(0600042 变成 600042)。请务必始终将其作为字符串处理。
3. The quirks: town names that aren’t town names
The town column isn’t always a real town. Japan Post’s readme lists a few special values: 以下に掲載がない場合 (“if not listed below”) — a catch-all code for the city. It does not identify a town. ○○の次に番地がくる場合 — the block number comes directly after the city name. ○○一円 — the whole municipality, with no town name. Inserting any of these into a user’s address is a bug. Clear them instead. Town names can also have a note in full-width parentheses, such as 大通西(1~19丁目) (“Ōdōri-nishi, 1st–19th chōme”). The note describes which block numbers belong to the code; the user types their own block number anyway. Keep the part before (: const cleanTown = (town) => { if (town === ‘以下に掲載がない場合’) return ”; if (/の次に番地がくる場合$/.test(town)) return ”; if (/一円$/.test(town)) return ”; return town.replace(/(.*$/, ”); // “大通西(1~19丁目)” → “大通西” };
3. 特性:并非町名的“町名”
“町”这一列并不总是真实的町名。日本邮政的自述文件列出了一些特殊值:以下に掲載がない場合(“如下所列之外”)——这是该市的一个统称代码,并不指代具体的町;○○の次に番地がくる場合——表示地号直接跟在市名之后;○○一円——表示整个行政区,没有具体的町名。将这些值插入用户的地址中是错误的,请将其清空。町名有时还会包含全角括号内的注释,例如 大通西(1~19丁目)。该注释描述了哪些地号属于该邮编,但用户通常会自己输入地号。请保留括号前的部分:const cleanTown = (town) => { if (town === '以下に掲載がない場合') return ''; if (/の次に番地がくる場合$/.test(town)) return ''; if (/一円$/.test(town)) return ''; return town.replace(/(.*$/, ''); // "大通西(1~19丁目)" → "大通西" };
4. Build step: CSV → small JSON files
More than 100,000 lines is too much to send to every visitor. Split the data by the first three digits of the postal code. The browser then loads only the small file it needs, such as /zip/100.json. // build-zip.mjs // 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(/(.*$/, ”); }; // Fields don’t contain ASCII commas, so a plain split is enough here. // Use a CSV library if you want to be extra safe. const parseLine = (line) => line.split(’,‘).map((f) => f.replace(/^”|”$/g, ”)); const files = {}; // { “100”: { “1000001”: [[“東京都”, “千代田区”, “千代田”]] } } for (const line of readFileSync(csvPath, ‘utf8’).split(/\r?\n/)) { if (!line) continue; const c = parseLine(line); const zip = c[2]; const entry = [c[6], c[7], cleanTown(c[8])]; const bucket = (files[zip.slice(0, 3)] ??= {}); const list = (bucket[zip] ??= []); // After cleaning, two rows can become identical — keep one. if (!list.some((e) => e.join() === entry.join())) list.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}); Each postal code maps to a list, because one code can cover several towns. Serve the folder as static files — no server code, no API key.
4. 构建步骤:CSV → 小型 JSON 文件
超过 10 万行的数据量对于每个访客来说太大了。请按邮政编码的前三位对数据进行拆分。这样浏览器只需加载所需的小文件,例如 /zip/100.json。(此处省略了构建脚本代码)。每个邮政编码映射到一个列表,因为一个编码可能覆盖多个町。将该文件夹作为静态文件托管——无需服务器代码,无需 API 密钥。
5. The form: fill in, but don’t fight the user
The HTML, with autocomplete attributes so browser autofill still works: (Many Japanese forms put the town at the start of the 番地 field instead of a separate field. Either works — keep it consistent with how you store addresses.) The script: const form = document.querySelector(‘form’); // “〒100-0001” → “1000001” (full-width digits, hyphens, the 〒 mark) const normalizeZip = (v) => v.normalize(‘NFKC’).replace(/[^0-9]/g, ”); const cache = {}; async function lookup(zip) { const key = zip.slice(0, 3); cache[key] ??= fetch(/zip/${key}.json).then((r) => (r.ok ? r.json() : {}));
5. 表单:自动填充,但不要干扰用户
HTML 代码应包含 autocomplete 属性,以便浏览器自动填充功能仍能正常工作。(此处省略了 HTML 示例)。许多日本表单将“町名”放在“番地”字段的开头,而不是单独设置一个字段。两种方式都可以——只要与你存储地址的方式保持一致即可。脚本部分:const form = document.querySelector('form');(此处省略了用于规范化邮编和执行查找的 JavaScript 代码)。