How to translate fields of a json?

Asked

Viewed 62 times

-2

I need to do a translation of the fields of a json. I want to inform as input a multidimensional json and as output receive another json with different fields, but remaining the values.

Input example:

{
  "nome": [
     {
       "sobrenome": "Potter",
       "primeiro_nome": [
          "Harry"
        ]
     }
  ],
  "sexo": "masculino",
  "nascimento": "1992-05-26"
}

Output example:

{
  "name": [
     {
       "family": "Potter",
       "given": [
          "Harry"
        ]
     }
  ],
  "gender": "masculino",
  "birthDate": "1992-05-26"
}

To solve the problem, I initially thought of generating a field relationship record to generate the translation (this record I intend to store in a database and use to perform the translation).

Example:

inbound               => outbund
nome[0].sobrenome     => name[0].family
nome[1].primeiro_nome => name[1].given[0]
sexo                  => gender
nascimento            => birthDate

My question is on how to read this inbound and outbound and generate the output json as specified above.

I would like to ask you nicely how you would solve this problem, I would like some ideas. If you got confused, I can improve the issue for a better understanding.

1 answer

0

then you want to translate the keys of a json, a loop on all keys can solve this, you can go replacing the keys by the respective translated values, eg:

// minha chave/valor da tradução
const traducao = {
    nome: "name",
    sobrenome: "family"
}

const json = {
    nome: [
        {
            sobrenome: "Potter"
        }
    ]
}

function keyTranslate(obj) {
    let res

    if (typeof(obj) != 'object') {
        return obj
    }

    res = Array.isArray(obj) ? [] : {}

    Object.keys(obj).forEach(key => {
        let k = traducao[key] || key
        res[k] = keyTranslate(obj[key])
    })
    
    return res
}

//
const meuJsonTraduzido = keyTranslate(json)

of course you can improve this code as poer example pass the translation json to the function

  • Thanks @Dev RR Nogueira, I’m applying here your solution to see what comes out.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.