大家好,这里是无所事事的XMB源码站^_^,今天为大家带来一篇本人亲自实操完成的一个小项目,作为一个技术菜,菜得不行的那种,喜欢在网上倒腾一些个源码进行研究学习,在刻苦学习的过程中,奈何英文水平着实有限,源码的本地化语言文件是Json格式的,一个一个翻译着实蛋疼,受限于翻译API的限制,网上的汉化工具大多要收费;作为一个技术研究人员,怎能容忍被别人薅羊毛!经过一段时间学习研究,利用JS+百度API搭建了一个静态网站来进行Json文件的翻译
这个翻译的原理是,解析Json文件,将需要翻译的键值通过百度翻译API得到翻译结果,再组装成翻译后的Json字符串,关键在于百度翻译API的调用不说废话了直接上干货
百度翻译API申请
http://api.fanyi.baidu.com/ 几分钟申请一个,身份认证后一个月免费100万字翻译;申请完后可以得到APP ID和密钥;
JavaScript代码
(function(e) {
function _(_) {
for(var r, s, n = _[0], i = _[1], l = _[2], p = 0, u = []; p < n.length; p++) s = n[p], a[s] && u.push(a[s][0]), a[s] = 0;
for(r in i) Object.prototype.hasOwnProperty.call(i, r) && (e[r] = i[r]);
c && c(_);
while(u.length) u.shift()();
return o.push.apply(o, l || []), t()
}
function t() {
for(var e, _ = 0; _ < o.length; _++) {
for(var t = o[_], r = !0, n = 1; n < t.length; n++) {
var i = t[n];
0 !== a[i] && (r = !1)
}
r && (o.splice(_--, 1), e = s(s.s = t[0]))
}
return e
}
var r = {},
a = {
app: 0
},
o = [];
function s(_) {
if(r[_]) return r[_].exports;
var t = r[_] = {
i: _,
l: !1,
exports: {}
};
return e[_].call(t.exports, t, t.exports, s), t.l = !0, t.exports
}
s.m = e, s.c = r, s.d = function(e, _, t) {
s.o(e, _) || Object.defineProperty(e, _, {
enumerable: !0,
get: t
})
}, s.r = function(e) {
"undefined" !== typeof Symbol && Symbol.toStringTag && Object.defineProperty(e, Symbol.toStringTag, {
value: "Module"
}), Object.defineProperty(e, "__esModule", {
value: !0
})
}, s.t = function(e, _) {
if(1 & _ && (e = s(e)), 8 & _) return e;
if(4 & _ && "object" === typeof e && e && e.__esModule) return e;
var t = Object.create(null);
if(s.r(t), Object.defineProperty(t, "default", {
enumerable: !0,
value: e
}), 2 & _ && "string" != typeof e)
for(var r in e) s.d(t, r, function(_) {
return e[_]
}.bind(null, r));
return t
}, s.n = function(e) {
var _ = e && e.__esModule ? function() {
return e["default"]
} : function() {
return e
};
return s.d(_, "a", _), _
}, s.o = function(e, _) {
return Object.prototype.hasOwnProperty.call(e, _)
}, s.p = "/";
var n = window["webpackJsonp"] = window["webpackJsonp"] || [],
i = n.push.bind(n);
n.push = _, n = n.slice();
for(var l = 0; l < n.length; l++) _(n[l]);
var c = i;
o.push([0, "chunk-vendors"]), t()
})({
0: function(e, _, t) {
e.exports = t("56d7")
},
"034f": function(e, _, t) {
"use strict";
var r = t("64a9"),
a = t.n(r);
a.a
},
"199c": function(module, __webpack_exports__, __webpack_require__) {
"use strict";
var core_js_modules_es6_regexp_constructor__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("3b2b"),
core_js_modules_es6_regexp_constructor__WEBPACK_IMPORTED_MODULE_0___default = __webpack_require__.n(core_js_modules_es6_regexp_constructor__WEBPACK_IMPORTED_MODULE_0__),
core_js_modules_es6_array_is_array__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__("2caf"),
core_js_modules_es6_array_is_array__WEBPACK_IMPORTED_MODULE_1___default = __webpack_require__.n(core_js_modules_es6_array_is_array__WEBPACK_IMPORTED_MODULE_1__),
F_DownGit_batch_translation_node_modules_babel_runtime_corejs2_helpers_esm_typeof__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__("7618"),
core_js_modules_es6_regexp_replace__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__("a481"),
core_js_modules_es6_regexp_replace__WEBPACK_IMPORTED_MODULE_3___default = __webpack_require__.n(core_js_modules_es6_regexp_replace__WEBPACK_IMPORTED_MODULE_3__),
F_DownGit_batch_translation_node_modules_babel_runtime_corejs2_helpers_esm_toConsumableArray__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__("75fc"),
core_js_modules_es6_regexp_to_string__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__("6b54"),
core_js_modules_es6_regexp_to_string__WEBPACK_IMPORTED_MODULE_5___default = __webpack_require__.n(core_js_modules_es6_regexp_to_string__WEBPACK_IMPORTED_MODULE_5__),
core_js_modules_es6_date_to_string__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__("87b3"),
core_js_modules_es6_date_to_string__WEBPACK_IMPORTED_MODULE_6___default = __webpack_require__.n(core_js_modules_es6_date_to_string__WEBPACK_IMPORTED_MODULE_6__),
core_js_modules_web_dom_iterable__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__("ac6a"),
core_js_modules_web_dom_iterable__WEBPACK_IMPORTED_MODULE_7___default = __webpack_require__.n(core_js_modules_web_dom_iterable__WEBPACK_IMPORTED_MODULE_7__),
core_js_modules_es6_array_for_each__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__("f3e2"),
core_js_modules_es6_array_for_each__WEBPACK_IMPORTED_MODULE_8___default = __webpack_require__.n(core_js_modules_es6_array_for_each__WEBPACK_IMPORTED_MODULE_8__),
md5__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__("6821f"),
md5__WEBPACK_IMPORTED_MODULE_9___default = __webpack_require__.n(md5__WEBPACK_IMPORTED_MODULE_9__),
clipboard__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__("b311"),
clipboard__WEBPACK_IMPORTED_MODULE_10___default = __webpack_require__.n(clipboard__WEBPACK_IMPORTED_MODULE_10__),
str_arr = [],
interval = 120;
function syntaxHighlight(e) {
return "string" != typeof e && (e = JSON.stringify(e, void 0, 2)), e = e.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">"), e.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function(e) {
var _ = "number";
return /^"/.test(e) ? _ = /:$/.test(e) ? "key" : "string" : /true|false/.test(e) ? _ = "boolean" : /null/.test(e) && (_ = "null"), '<span class="' + _ + '">' + e + "</span>"
})
}
function isJSON(e) {
if("string" == typeof e) try {
var _ = JSON.parse(e);
return !("object" != Object(F_DownGit_batch_translation_node_modules_babel_runtime_corejs2_helpers_esm_typeof__WEBPACK_IMPORTED_MODULE_2__["a"])(_) || !_)
} catch (t) {
return !1
}
}
function parseJson(e) {
var _ = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : null;
for(var t in e)
if("object" == Object(F_DownGit_batch_translation_node_modules_babel_runtime_corejs2_helpers_esm_typeof__WEBPACK_IMPORTED_MODULE_2__["a"])(e[t])) {
var r = "";
r = _ ? "".concat(_, "['")
.concat(t, "']") : "['".concat(t, "']"), parseJson(e[t], r)
} else _ ? str_arr.push("".concat(_, "['")
.concat(t, "']")) : str_arr.push("['".concat(t, "']"));
return str_arr
}
function addToast(e) {
var _ = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : "success";
$.Toast("提示", e, _, {
stack: !0,
has_icon: !1,
has_close_btn: !0,
fullscreen: !1,
timeout: 3e3,
sticky: !1,
has_progress: !0,
rtl: !1
})
}
function deepClone(e) {
var _;
if("object" === Object(F_DownGit_batch_translation_node_modules_babel_runtime_corejs2_helpers_esm_typeof__WEBPACK_IMPORTED_MODULE_2__["a"])(e))
if(Array.isArray(e))
for(var t in _ = [], e) _.push(deepClone(e[t]));
else if(null === e) _ = null;
else if(e.constructor === RegExp) _ = e;
else
for(var r in _ = {}, e) _[r] = deepClone(e[r]);
else _ = e;
return _
}
__webpack_exports__["a"] = {
name: "app",
data: function() {
return {
wxpay: "http://127.0.0.1",
alipay: "http://127.0.0.1",
srcList: ["http://127.0.0.1", "http://127.0.0.1"],
dialogFormVisible: !1,
form: {
appid: "需要填申请的APP ID",
key: "需要填申请的Key"
},
rules: {
appid: [{
required: !0,
message: "请输入appid",
trigger: "blur"
}],
key: [{
required: !0,
message: "请输入key",
trigger: "blur"
}]
},
old_text: "",
old_json: "",
old_json_html: "",
new_json: "",
err_arr: [],
auto_code: "zh",
from_code: "en"
}
},
mounted: function() {
this.ToClipboard(), this.form.appid && this.form.key || (this.dialogFormVisible = !0)
},
methods: {
onInput: function onInput() {
if("" == this.old_text) return this.old_json = "", this.old_json_html = "", !1;
this.old_text = JSON.stringify(eval("(" + this.old_text + ")")), this.old_json = eval("(" + this.old_text + ")"), isJSON(this.old_text) ? (this.old_json = JSON.parse(this.old_text), this.old_json_html = syntaxHighlight(this.old_json)) : (this.old_json = "输入的不是JSON数据", this.old_json_html = "输入的不是JSON数据")
},
fanyi: function fanyi(to) {
var vm = this;
if(!this.form.appid || !this.form.key) return this.$message.error("请配置appid及key参数"), !1;
if("" == this.old_json || "{}" == JSON.stringify(this.old_json)) return this.$message.error("请输入待翻译的JSON"), !1;
"auto" == to && (to = this.auto_code), this.new_json = deepClone(this.old_json), str_arr = [], this.err_arr = [];
var arr = parseJson(vm.new_json);
arr.forEach(function(e, index) {
setTimeout(function() {
var tmp = Date.parse(new Date)
.toString();
tmp = tmp.substr(0, 10);
var k = eval("vm.new_json".concat(e)),
params = {
q: k,
from: vm.from_code,
to: to,
appid: vm.form.appid,
salt: tmp,
sign: ""
},
sign = vm.form.appid + params.q + params.salt + vm.form.key;
sign = md5__WEBPACK_IMPORTED_MODULE_9___default()(sign), params.sign = sign;
var api_url = "https://api.fanyi.baidu.com/api/trans/vip/translate?q=" + params.q + "&from=" + params.from + "&to=" + params.to + "&appid=" + vm.form.appid + "&salt=" + params.salt + "&sign=" + params.sign;
vm.$http.get(api_url)
.then(function(res) {
(res.data.error_msg || res.data.error_code) && vm.$notify({
title: res.data.error_code,
message: res.data.error_msg,
type: "warning"
}), res.data.trans_result[0]["dst"] ? eval("vm.new_json".concat(e, ' = "')
.concat(res.data.trans_result[0]["dst"], '"')) : vm.err_arr = [].concat(Object(F_DownGit_batch_translation_node_modules_babel_runtime_corejs2_helpers_esm_toConsumableArray__WEBPACK_IMPORTED_MODULE_4__["a"])(vm.err_arr), [k])
})
.catch(function(e) {
vm.err_arr = [].concat(Object(F_DownGit_batch_translation_node_modules_babel_runtime_corejs2_helpers_esm_toConsumableArray__WEBPACK_IMPORTED_MODULE_4__["a"])(vm.err_arr), [k])
})
}, index * interval)
})
},
ToClipboard: function() {
var e = this,
_ = document.getElementsByClassName("btn01"),
t = new clipboard__WEBPACK_IMPORTED_MODULE_10___default.a(_);
t.on("success", function(_) {
e.$message({
message: "复制成功",
type: "success"
})
}), t.on("error", function(_) {
e.$message({
message: "复制失败",
type: "warning"
})
})
},
onConfig: function() {
var e = this;
this.$refs.form.validate(function(_) {
if(!_) return console.log("error submit!!"), !1;
e.dialogFormVisible = !1
})
}
}
}
},
"56d7": function(e, _, t) {
"use strict";
t.r(_);
t("cadf"), t("551c"), t("f751"), t("097d");
var r = t("2b0e"),
a = function() {
var e = this,
_ = e.$createElement,
t = e._self._c || _;
return t("div", {
staticClass: "page-wrap",
attrs: {
id: "app"
}
}, [t("div", {
staticClass: "title-line"
}, [t("h3", [e._v("JSON批量翻译工具(兼容key没有双引括起来的JSON字符串解析)")]), t("el-link", {
attrs: {
href: "https://api.fanyi.baidu.com/doc/21",
target: "_blank",
type: "danger"
}
}, [e._v("查看参考语种")])], 1), t("el-row", {
staticClass: "top",
attrs: {
gutter: 10
}
}, [t("el-col", {
attrs: {
span: 12
}
}, [t("textarea", {
directives: [{
name: "model",
rawName: "v-model",
value: e.old_text,
expression: "old_text"
}],
staticClass: "input-textarea",
attrs: {
placeholder: "请输入要翻译的JSON数据,默认英文"
},
domProps: {
value: e.old_text
},
on: {
input: [function(_) {
_.target.composing || (e.old_text = _.target.value)
}, function(_) {
return e.onInput()
}]
}
})]), t("el-col", {
attrs: {
span: 12
}
}, [t("pre", {
staticClass: "to-json",
domProps: {
innerHTML: e._s(e.old_json_html)
}
})])], 1), t("el-row", {
staticClass: "btn-line",
attrs: {
gutter: 20
}
}, [t("el-col", {
attrs: {
span: 3
}
}, [t("el-input", {
staticStyle: {
width: "100%"
},
attrs: {
type: "primary",
placeholder: "翻译的语言代码"
},
model: {
value: e.from_code,
callback: function(_) {
e.from_code = _
},
expression: "from_code"
}
})], 1), t("el-col", {
attrs: {
span: 3
}
}, [t("el-input", {
staticStyle: {
width: "100%"
},
attrs: {
type: "primary",
placeholder: "结果的语言代码"
},
model: {
value: e.auto_code,
callback: function(_) {
e.auto_code = _
},
expression: "auto_code"
}
})], 1), t("el-col", {
attrs: {
span: 3
}
}, [t("el-button", {
attrs: {
type: "primary"
},
on: {
click: function(_) {
return e.fanyi("auto")
}
}
}, [e._v("开始翻译")])], 1)], 1), t("el-row", {
staticClass: "new-json-view"
}, [t("el-col", [t("pre", {
staticClass: "to-json",
attrs: {
id: "bar"
},
domProps: {
innerHTML: e._s(e.new_json)
}
})])], 1), t("el-row", {
staticClass: "btn-line",
attrs: {
gutter: 20
}
}, [t("el-col", {
attrs: {
span: 3
}
}, [t("el-button", {
staticClass: "btn01",
attrs: {
type: "success",
"data-clipboard-target": "#bar"
}
}, [e._v("复制")])], 1)], 1), e.err_arr.length ? t("h3", {
staticClass: "err-text"
}, [e._v("以下文字未翻译"), t("span", [e._v("(如果所有单词都未翻译,请检查appid或key配置是否正确,或者查看F12 -> Network定位错误原因)")])]) : e._e(), e.err_arr.length ? t("el-row", {
staticClass: "new-json-view"
}, [t("el-col", [t("pre", {
staticClass: "to-json",
attrs: {
id: "bar"
},
domProps: {
innerHTML: e._s(e.err_arr)
}
})])], 1) : e._e(), t("el-row", {
staticClass: "btn-line",
attrs: {
gutter: 24
}
}, [t("el-col", {
staticClass: "tips",
attrs: {
span: 18
}
}, [t("p", [e._v("1.支持JSON字符串键值批量翻译,默认初始语言为en")]), t("br"), t("p", [e._v("2.兼容key没有双引括起来的JSON字符串解析")]), t("br"), t("p", [e._v("3.支持百度翻译完整语种")]), t("br")])], 1), t("el-dialog", {
attrs: {
title: "配置",
visible: e.dialogFormVisible
},
on: {
"update:visible": function(_) {
e.dialogFormVisible = _
}
}
}, [t("el-form", {
ref: "form",
attrs: {
model: e.form,
rules: e.rules
}
}, [t("el-form-item", {
attrs: {
label: "appid",
"label-width": "80px",
prop: "appid"
}
}, [t("el-input", {
attrs: {
autocomplete: "off"
},
model: {
value: e.form.appid,
callback: function(_) {
e.$set(e.form, "appid", _)
},
expression: "form.appid"
}
})], 1), t("el-form-item", {
attrs: {
label: "key",
"label-width": "80px",
prop: "key"
}
}, [t("el-input", {
attrs: {
autocomplete: "off"
},
model: {
value: e.form.key,
callback: function(_) {
e.$set(e.form, "key", _)
},
expression: "form.key"
}
})], 1)], 1), t("div", {
staticClass: "tips"
}, [t("p", [e._v("1、注册百度翻译开放平台账号 "), t("a", {
attrs: {
href: "https://api.fanyi.baidu.com/",
target: "_blank"
}
}, [e._v("https://api.fanyi.baidu.com/")]), e._v(",并进行实名认证")]), t("p", [e._v("2、开通通用翻译API服务"), t("a", {
attrs: {
href: "https://fanyi-api.baidu.com/choose",
target: "_blank"
}
}, [e._v("开通链接")])]), t("p", [e._v("3、在"), t("a", {
attrs: {
href: "https://api.fanyi.baidu.com/manage/developer",
target: "_blank"
}
}, [e._v("开发者中心")]), e._v(",设置通用翻译服务信息的服务器地址,填写成"), t("a", {
attrs: {
href: "https://ip.cn/",
target: "_blank"
}
}, [e._v("本机网络IP")])])]), t("div", {
staticClass: "dialog-footer",
attrs: {
slot: "footer"
},
slot: "footer"
}, [t("el-button", {
on: {
click: function(_) {
e.dialogFormVisible = !1
}
}
}, [e._v("取 消")]), t("el-button", {
attrs: {
type: "primary"
},
on: {
click: function(_) {
return e.onConfig()
}
}
}, [e._v("确 定")])], 1)], 1)], 1)
},
o = [],
s = t("199c"),
n = s["a"],
i = (t("034f"), t("2877")),
l = Object(i["a"])(n, a, o, !1, null, null, null),
c = l.exports,
p = t("5c96"),
u = t.n(p),
d = (t("0fae"), t("bc3a")),
f = t.n(d);
r["default"].use(u.a), r["default"].prototype.$http = f.a, r["default"].config.productionTip = !1, new r["default"]({
render: function(e) {
return e(c)
}
})
.$mount("#app")
},
"64a9": function(e, _, t) {}
});
//# sourceMappingURL=app.373d9aa7.js.map
HTML首页代码(引用JS)
<!DOCTYPE html><html lang=en><head><meta charset=utf-8><meta http-equiv=X-UA-Compatible content="IE=edge"><meta name=viewport content="width=device-width,initial-scale=1"><link rel=icon href=./favicon.ico><title>JSON自助翻译</title><link href=./css/app.67cf251f.css rel=preload as=style><link href=./css/chunk-vendors.bfd3a0d2.css rel=preload as=style><link href=./js/app.373d9aa7.js rel=preload as=script><link href=./js/chunk-vendors.9b649ebd.js rel=preload as=script><link href=./css/chunk-vendors.bfd3a0d2.css rel=stylesheet><link href=./css/app.67cf251f.css rel=stylesheet></head><body><noscript><strong>We're sorry but default doesn't work properly without JavaScript enabled. Please enable it to continue.</strong></noscript><div id=app></div><script src=./js/chunk-vendors.9b649ebd.js></script><script src=./js/app.373d9aa7.js></script></body></html>
总结
- 跨域问题,页面文件放服务器上访问,通过http.get() 请求百度翻译api不通过,将url请求地址改为服务器域名,然后配置ngnix反向代理即可成功
- 这个代码是逐个Json键值请求API接口返回,实时更新翻译结果,效果挺不错
如果需要完整文件包,请下载
资源下载
下载价格25 米币
会员 5折、钻石会员免费
请先登录下载说明:
1、如遇购买或下载问题,请联系在线客服 ; 2、本站资源来源于互联网,未测试源码不保证100%能部署,不包含技术支持,请酌情下载; 3、本站不售卖代码,所有发布的文章以及附件仅限用于学习和研究目的;不得用于商业或者非法用途;如果您喜欢该程序,请支持正版软件,购买注册,得到更好的正版服务。否则由此产生的法律后果,本站概不负责! 4、本站收益用于平台服务器、云存储CDN、人力等网站运营成本,支持本站请订阅本站会员,您的支持是我们更新内容的最大动力!原文链接:https://www.xmbcode.com/guide/1736/,转载请注明出处。