不同语言JSON的响应API



im在尝试从我的API以所选语言从标题做出响应时遇到问题:

接受语言:es MX或接受语言:en-US

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

好吧,我得到了正确的语言,但我不知道如何发送json,只使用所选语言的数据。回复给我两种颜色。

我的JSON示例:

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

也许这个解决方案对您有所帮助。

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)

我更喜欢使用类似本地化模块的东西

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 

欲了解更多详细信息,请阅读https://github.com/AGROSICA/node-localize

为所选语言创建函数,如:

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)

相关内容

  • 没有找到相关文章

最新更新