0

I have a JSON like this:

{
  "generic": {
    "tables": {
      "header": "Header",
      "columns": "Columns"
    },
    "yes": "Yes",
    "no": "No"
  }
}

But with thousands of lines and more nested objects. I need to translate all this strings, so I'm making a script to do it. How can I loop through each string and replace it with something?

I've searched and found this thread: Looping through JSON with node.js but I can't find any solution that fits my needs.

I made this quick script:

const fs = require('fs');
const obj = JSON.parse(fs.readFileSync('en.json', 'utf-8'));

const translate = (obj, path = '') => {
  const keys = Object.keys(obj);

  keys.forEach((key) => {
    const type = typeof obj[key];

    if (type === 'object') {
      translate(obj[key], path === '' ? key : path + '.' + key);
    } else {
      console.log(path + ' --> [' + key + ']: ' + obj[key]);
    }
  });
};

translate(obj);

It loops through the array. In the console log line I have the full path of the translation item (i.e.: 'generic.tables.header') and I have the key and value of the translation.

How can i make a new object containing the keys ?

ddor254
  • 1,570
  • 1
  • 12
  • 28
nick
  • 2,819
  • 5
  • 33
  • 69

1 Answers1

0

I think I found a way, instead of saving the path, create an empty object and insert the keys there:

const fs = require('fs');
const obj = JSON.parse(fs.readFileSync('en.json', 'utf-8'));

const newObj = {};

const translate = (obj, path = '', objVal) => {
  const keys = Object.keys(obj);

  keys.forEach((key) => {
    const type = typeof obj[key];

    if (type === 'object') {
      objVal[key] = {};
      const newObjVal = objVal[key];

      translate(obj[key], path === '' ? key : path + '.' + key, newObjVal);
    } else {
      objVal[key] = obj[key];
      //console.log(path + ' --> [' + key + ']: ' + obj[key]);
    }
  });
};

translate(obj, '', newObj);
nick
  • 2,819
  • 5
  • 33
  • 69