I have some JSON’s as language files. I would like to get the JSON content and associate with a variable. I try:
function getLangJson(lang){
if(lang == 'pt-BR'){
var jsonFile = 'pt-BR.json';
}
else if(lang == 'en-US'){
var jsonFile = 'en-US.json'
}
app.request.json('lang/'+jsonFile)
.then(function (res) {
var json = res.data;
})
return json;
}
thejson = getLangJson('pt-BR');
But I just receive a json is not defined
message. How can I get the JSON and save inside a variable to use at whole code?
Thanks
I think you need to define var json like this
function getLangJson(lang){
var json;
if(lang == 'pt-BR'){
var jsonFile = 'pt-BR.json';
}
else if(lang == 'en-US'){
var jsonFile = 'en-US.json'
}
app.request.json('lang/'+jsonFile)
.then(function (res) {
json = res.data;
})
return json;
}
thejson = getLangJson('pt-BR');
Not works… I receive ‘undefined’… I tried:
function get_lang_file(lang){
var jsonContent;
app.request.json('lang/'+lang+'.json', function(json){
jsonContent = json;
})
return jsonContent;
}
var json = get_lang_file('pt-BR');
console.log(json);
And I receive ‘undefied’ too =/
app.request works in async way and returns promise, you need to use async syntax
The follow code it’s working and now the JSON file content is inside a variable
function get_lang_file(lang){
var json;
app.request({
url: 'lang/'+lang+'.json',
method: "POST",
cache: false,
async: false,
//contentType: "application/x-www-form-urlencoded",
dataType: "json",
processData: true,
success:function (data, status, xhr){
json = data;
},
error: function (xhr, status, message){
}
});
return json;
}
var langFileContent = get_lang_file(localStorage.language);
Thanks 
1 Like