简体   繁体   中英

Response API in different languages JSON

im having an issue trying to make a response from my API in the selected language from the header with:

Accept-Language: es-MX or Accept-Language: en-US

function getLanguage (req, res, next) {
  let lang = req.acceptsLanguages('en-US', 'es-ES');
  console.log(lang)
  next()
}

app.use(getLanguage)

Well, i got the correct language but i dont know how to send the json with only the data in the selected language. The response send me both colors.

Example of my JSON:

"teams": [
  {
    "id": 0,
     "color": {
        "en": "Blue",
        "es": "Azul"
      }
    },
    {
     "id": 1,
     "color": {
        "en": "Red",
        "es": "Rojo"
    }
  }
]

maybe this solucion help you.

 let lang = "en" let teams= [ { "id": 0, "color": { "en": "Blue", "es": "Azul" } }, { "id": 1, "color": { "en": "Red", "es": "Rojo" } } ] teams = teams.map(item => { item.color = item.color[lang] return item }) console.log(teams)

I would prefer using something like localize module

var Localize = require('localize');

var myLocalize = new Localize({"color": {
        "en": "Blue",
        "es": "Azul",
        "de" : "Blau"
      }
     });

myLocalize.setLocale("es")
console.log(myLocalize.translate("color")); // prints Azul 
myLocalize.setLocale("de")
console.log(myLocalize.translate("color")); // prints Blau 

For further details read https://github.com/AGROSICA/node-localize

Create function for selected language like:

 const teamsOnString = `[ { "id": 0, "color": { "en": "Blue", "es": "Azul" } }, { "id": 1, "color": { "en": "Red", "es": "Rojo" } } ]` const teamsOnJson = JSON.parse(teamsOnString) function selectLanguage(lang) { let filteredLang = teamsOnJson.map((items) => { items.color = items.color[lang] return items }) return filteredLang } let enLanguage = selectLanguage('en') console.log(enLanguage)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM