Write a Go program to convert PO files to JSON format. The data of JSON
format can be passed to front-end by web servers to translate a text string into
the user's native language. You can use the JSON data from PO files to
implement gettext function in browsers.
In this example, we support two locale, zh_TW (Traditional Chinese) and
vi_VN (Vietnamese). The zh_TW PO file are located at
locale/zh_TW/LC_MESSAGES/messages.po and vi_VN PO file are located at
locale/vi_VN/LC_MESSAGES/messages.po.
zh_TW PO file locale/zh_TW/LC_MESSAGES/messages.po:
# Chinese translations for PACKAGE package.# Copyright (C) 2013 THE PACKAGE'S COPYRIGHT HOLDER# This file is distributed under the same license as the PACKAGE package.# Automatically generated, 2013.#msgid""msgstr"""Project-Id-Version: PACKAGE VERSION\n""Report-Msgid-Bugs-To: \n""POT-Creation-Date: 2013-06-04 10:20+0800\n""PO-Revision-Date: 2013-03-10 05:19+0800\n""Last-Translator: Automatically generated\n""Language-Team: none\n""Language: zh_TW\n""MIME-Version: 1.0\n""Content-Type: text/plain; charset=UTF-8\n""Content-Transfer-Encoding: 8bit\n"msgid"Home"msgstr"首頁"msgid"Canon"msgstr"經典"msgid"About"msgstr"關於"msgid"Setting"msgstr"設定"msgid"Translation"msgstr"翻譯"
vi_VN PO file locale/vi_VN/LC_MESSAGES/messages.po:
packagepo2jsonimport"regexp"import"io/ioutil"import"encoding/json"typemsgIdStrPairsmap[string]stringtypelocalesMsgmap[string]msgIdStrPairsconstpattern=`msgid "(.+)"\nmsgstr "(.+)"`funcgetPOPath(locale,domain,localedirstring)string{returnlocaledir+"/"+locale+"/LC_MESSAGES/"+domain+".po"}funcextractFromPOFile(popathstring)msgIdStrPairs{buf,err:=ioutil.ReadFile(popath)iferr!=nil{panic(err)}re:=regexp.MustCompile(pattern)matches:=re.FindAllStringSubmatch(string(buf),-1)pairs:=msgIdStrPairs{}for_,array:=rangematches{pairs[array[1]]=array[2]}returnpairs}funcPO2JSON(locales[]string,domain,localedirstring)string{// create PO-like json data for i18nobj:=localesMsg{}for_,locale:=rangelocales{// English is default languageiflocale=="en_US"{continue}obj[locale]=extractFromPOFile(getPOPath(locale,domain,localedir))}b,err:=json.Marshal(obj)iferr!=nil{panic(err)}returnstring(b)}