S
S
speculant2018-08-02 19:52:27
JavaScript
speculant, 2018-08-02 19:52:27

How to output text from json to certain places depending on language?

Hello, I need help.
There is a json file like this. It is required to display the desired element in its place when choosing a language.
I put an id on the language button, when I click I define it, then I look for places with the .lang class and determine their keys by which I pull out the desired translation from json, but I don’t understand how to do it right)

{
  "_id" : "post",
  "en" : 
    {
      "post" : "Post",
      "news" : "News"
    },
  "ru" :
    {
      "post" : "Посты",
      "news" : "Новости"
    }
},
{
  "_id" : "menu",
  "en" : 
    {
      "post" : "menu1",
      "news" : "menu2"
    },
  "ru" :
    {
      "post" : "меню1",
      "news" : "меню2"
    }
}

var requestURL = 'lang.json';
  var request = new XMLHttpRequest();
  request.open('GET', requestURL);
  request.responseType = 'json';
  request.send()

  request.onload = function() {
  var obj = request.response;
  eng(obj);
  }

  $(function eng(jsonObj){
    $('.translate').click(function(){
      var lang = $(this).attr('id');

      $('.lang').each(function(index, element){
        $(this).text(jsonObj[lang][$(this)]);
      });
    });
  });

<li id="en">En</li>
  <li id="ru">Русский</li>

  <a  class="lang" key="post" href="***">Посты</a>
  <a  class="lang" key="news" href="***">Новости</a>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton fon Faust, 2018-08-03
@speculant

Firstly, here json is not correct, because either it is not an object, but an array, or no "_id" is needed.
It should be:

{
  "post": {
      "en" : {
          "post" : "Post",
          "news" : "News"
        },
      "ru" : {
          "post" : "Посты",
          "news" : "Новости"
        }
    },
    "menu": {
      "en" : {
          "post" : "menu1",
          "news" : "menu2"
       },
      "ru" : {
          "post" : "меню1",
          "news" : "меню2"
       }
    }
}

Second, if you're using jquery, why do you need XMLHttpRequest gardening? jquery has excellent human-readable ajax support.
var lang = "ru"; // захардкодил, для простоты

$.get({
    url: "lang.json",
    dataType: "json",
    success: function(data) {
        $(".lang").each(function(entry){
            var $el = $(this);
            var text = data[$el.attr("key")][lang];
            $el.text(text);
        });
    }
})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question