artworkad シ artworkad シ - 4 months ago 14
Javascript Question

Pass JSON from php to javascript

I want to localize my webapp. Since localization through javascript only is not recommended I thought using php would be an alternative.

So with php I read a

file that stores all localization data.

$json = file_get_contents("_locales/en/messages.json");

In the header of my webapp I generate some javascript with php according to the user's browser language.

echo "var localeObj = " . $json . ";";

So this is just a var that holds all data from the m
file that looks like that

"extTitle": {
"message": "Test1"
"message": "Test2"

Now I want to be able to access each item from the json like

var title = getItem("extTitle");

and it returns
. Any idea how to do that?

I am not very familar with json but if I just alert the
it gives me just [object Object].

var getItem = function(item) {
   return localObj[item].message;

You could always encapsulate your i18n strings too...

(function() {

   var localObj = { ... };

   window.getItem = function(item) {
       return localObj[item].message;


This way, no other variables can possibly clobber your localObj.