javascript - 如何使用nodejs构建从nodejs脚本输出的json文件?

标签 javascript node.js

我正在使用nodejs脚本将json文件从英语翻译成法语。翻译正在输出到 fr.json 文件中,但不是我需要的格式。

这是我要翻译的输入 en.json 文件:

[
  {
    "id": "EnterEmailForm.pleaseRegisterHere",
    "defaultMessage": "Email was not found, please register here",
    "filepath": "./src/accounts/components/EnterEmailForm/EnterEmailForm.js"
  },
  {
    "id": "EnterEmailForm.alreadyHaveAnAccount",
    "defaultMessage": "Already have an account?",
    "filepath": "./src/accounts/components/EnterEmailForm/EnterEmailForm.js"
  }
]

这是我需要的输出 fr.json 格式,(只是 id 和 defaultMessage 的值):

{
  "EnterEmailForm.pleaseRegisterHere": "Email n'a pas été       trouvé, veuillez vous inscrire ici",
  "EnterEmailForm.alreadyHaveAnAccount": "Vous avez déjà un compte?",
}

这是脚本给我的输出 fr.json:

{
  "0": {
    "id": "EnterEmailForm.pleaseRegisterHere",
    "defaultMessage": "Email n'a pas été trouvé, veuillez vous inscrire ici",
    "filepath": "./src/accounts/components/EnterEmailForm/EnterEmailForm.js"
  },
  "1": {
    "id": "EnterEmailForm.alreadyHaveAnAccount",
    "defaultMessage": "Vous avez déjà un compte?",
    "filepath": "./src/accounts/components/EnterEmailForm/EnterEmailForm.js"
  }
}

这是将 en.json 文件转换为 fr.json 文件的脚本:

#!/usr/bin/env node

const fs = require('fs');
const moment = require('moment');
const _ = require('lodash');
const path = require('path');
const agent = require('superagent-promise')(require('superagent'), Promise);

//Lang Codes https://ctrlq.org/code/19899-google-translate-languages

if (process.argv.length >= 5) {

    //Args
    const apiKey = process.argv[2];
    const inputFile = process.argv[3];
    const destinationCodes = process.argv[4].split(',');

    const apiUrl = _.template('https://www.googleapis.com/language/translate/v2?key=<%= apiKey %>&q=<%= value %>&source=en&target=<%= languageKey %>');

    function transformResponse(res) {
        return _.get(JSON.parse(res.text), [ 'data', 'translations',  0, 'translatedText' ]);
    }

    function iterLeaves(value, keyChain, accumulator, languageKey) {
        accumulator = accumulator || {};
        keyChain = keyChain || [];
        if (_.isObject(value)) {
            return _.chain(value).reduce((handlers, v, k) => {
                return handlers.concat(iterLeaves(v, keyChain.concat(k), accumulator, languageKey));
            }, []).flattenDeep().value();
        } else {
            return function () {
                console.log(_.template('Translating <%= value %> to <%= languageKey %>')({value, languageKey}));

                //Translates individual string to language code
                return agent('GET', apiUrl({
                    value: encodeURI(value),
                    languageKey,
                    apiKey
                })).then(transformResponse).then((text) => {
                    //Sets the value in the accumulator
                    _.set(accumulator, keyChain, text, );

                    //This needs to be returned to it's eventually written to json
                    return accumulator;
                });
            };
        }
    }

    Promise.all(_.reduce(destinationCodes, (sum, languageKey) => {
        const fileName = _.template('/tmp/<%= languageKey %>.json')({
            languageKey,
        });

        //Starts with the top level strings
        return sum.concat(_.reduce(iterLeaves(JSON.parse(fs.readFileSync(path.resolve(inputFile), 'utf-8')), undefined, undefined, languageKey), (promiseChain, fn) => {
            return promiseChain.then(fn);
        }, Promise.resolve()).then((payload) => {
            fs.writeFileSync(fileName, JSON.stringify(payload, null, 2));
        }).then(_.partial(console.log, 'Successfully translated all nodes, file output at ' + fileName)));
    }, [])).then(() => {
        process.exit();
    });

} else {
    console.error('You must provide an input json file and a comma-separated list of destination language codes.');
}

如何编辑脚本以将输出文件 fr.json 正确格式化为我需要的格式?

最佳答案

获得当前生成的对象后,您可以通过将对象的值减少到另一个对象(其键是id)来将其转换为所需的输出其值为 defaultMessage:

const payload = {
  "0": {
    "id": "EnterEmailForm.pleaseRegisterHere",
    "defaultMessage": "Email n&#39;a pas été trouvé, veuillez vous inscrire ici",
    "filepath": "./src/accounts/components/EnterEmailForm/EnterEmailForm.js"
  },
  "1": {
    "id": "EnterEmailForm.alreadyHaveAnAccount",
    "defaultMessage": "Vous avez déjà un compte?",
    "filepath": "./src/accounts/components/EnterEmailForm/EnterEmailForm.js"
  }
};
const output = Object.values(payload).reduce((a, { id, defaultMessage }) => {
  a[id] = defaultMessage;
  return a;
}, {});
console.log(output);

关于javascript - 如何使用nodejs构建从nodejs脚本输出的json文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53255326/

相关文章:

javascript - Highcharts yaxis 价格线

node.js - 自定义异常名称而不是 UserLambdaValidationException

node.js - 如果应用程序被机器人访问,请不要启动 session

javascript - node.js上传下载pdf文件

javascript - Angular 中 ng-show 和 ng-hide 的行为

javascript - font-face Styled 组件 - OTS 解析错误 : invalid version tag

node.js - Docker 等待 Web 应用程序启动(依赖项)

node.js - macos 上用于 sails js 开发的 Docker 图像挂起

javascript - 使用frameRate和帧计数器的定时器可靠吗?

javascript - ng-repeat 中的 Angular 单选按钮模型