Using JSON for Language-independent Configuration Files

The growing availability of JSON parsing in server-side frameworks elevates the usefulness of JavaScript beyond client-side programming, to providing base syntax for a generalized data interchange format. Well duh.

But a not-immediately-obvious advantage of this is the ability to have language-independent configuration files for Ajax development.

In a nutshell — a JavaScript object-literal can be parsed as JSON with (say) PHP to create a corresponding associative array.

Consider a simple config object like this:

const config = {  'lang' : 'en',      'host' : 'sitepoint.com'    };

We can include that in a regular <script> and get access to its properties with JavaScript:

alert(config['lang']);    //outputs "en"

All good. But we can also import it into PHP and parse it like this:

$datastring = file_get_contents('config.js');  $regexes = array(     array("p"=>"/[w]*(//).*$/m", "r"=>""),    //remove comments   array("p"=>"/'/m", "r"=>""")                //replace single-quotes with double-quotes    );    foreach($regexes as $regex) {     $datastring = preg_replace($regex['p'], $regex['r'], $datastring);  }  preg_match("/config[ ]?=[ ]?{([^;]+)\;/", $datastring, $matches);  $config = json_decode('{' . $matches[1], true);

And then we have that same data in a PHP associative array:

echo $config['lang'];    //outputs "en"

Availability of JSON parsing in PHP

The native functions json_encode and json_decode were not added to PHP until Version 5.2. If you’re using an earlier version you’ll need to implement them yourself, and for this I’d recommend Michal Migurski’s JSON Services class. The only disadvantage of this is that it only supports conversion to an object, not to an associative array (as triggered by the true flag in the native functions).

However you can fix that with recursive object to array conversion. Here’s a litte snippet to do that; I didn’t write this, but I’m afraid I can’t remember where I found it either:

function object_to_array($data)  {     if(is_array($data) || is_object($data))     {       $result = array();          foreach($data as $key => $value)         {           $result[$key] = object_to_array($value);        }       return $result;     }   return $data; }

Then you’ll be able to do the original conversion like this:

$config = object_to_array(json_decode('{' . $matches[1]));

Conclusion

The advantage of this is obvious — both the client-side and server-side layers of an application can get their configuration data from a single managed source.

Replay

Category: javascript Time: 2008-08-21 Views: 3
Tags:

Related post

  • Use git for multiple server configuration files 2011-03-21

    We have migrated a lot of source code over to git and are very happy with our current solution. We would like to have our server configuration files versioned on the same system, but there are a few things that don't work the way we would like it to

  • phpinfo.php is not showing extra folder for additional PHP configuration files 2013-06-07

    My phpinfo.php is not showing extra folder for additional PHP configuration files. I am running Apache v2.4.4(with PHP DSO) and PHP v5.4.14 on CentOS v6.3 32-bit. Apache and PHP installations are compiled from source. I have not used the configure op

  • What syntax highlighting should I use for a Nagios configuration file? 2012-08-28

    What syntax highlighting should I use with nagios configuration files? Textmate has a lot of options for syntax highlighting but I can't find one that works. I've tried using the Apache2 syntax, among others, and I just thing there must be something

  • Language agnostic configuration file format 2011-07-12

    Many projects these days use more than one programming / scripting language, and in standard DRY tradition these should not have separate configuration files if they need the same information. After a small survey in /etc, it looks like a lot of inco

  • What is the order of precedence for RedHat network configuration files? 2010-10-10

    This has been bugging me for some time, because I haven't bothered to sit down and write down what exactly is going on. Our RedHat server network configuration is all over the map. Across a fleet of servers installed RH4 and RH5, sometimes we manage

  • Debugging Java program for changing timezone configuration file on Ubuntu 2011-07-07

    Here is a ruby script I wrote to change the timezone configuration on Ubuntu. I run it with jruby (a Ruby interpreter running in a JVM). require 'java' if ARGV.length == 0 puts "Usage: jruby change_timezone.rb America/Toronto" exit end old_zone

  • Make apt-get (or aptitude) run with -y but not prompt for replacement of configuration files? 2012-02-16

    When running apt-get -y install <packages ...> on Ubuntu 10.04 I would like apt-get (or aptitude if that makes it easier) to not prompt me when installing additional dependencies (behavior of -y as I understand it) and but not prompt me about overwr

  • language locales configuration file 2013-09-19

    Ubuntu, where is the Locales configuration file. I want to leave en_us_utf8 and remove others like en_GB or en_zimbabwe. Is it the locale-archive file /usr/lib/locale, because I can't open this file. --------------Solutions------------- If you like t

  • Scraping and using JSON data from thousands of files in a directory 2015-10-21

    I have a few thousand json files containing order histories sitting in a directory from one of our systems. Since customers can opt in to receive marketing I'm opening each json file and then processing the data to scrape our active subscribers. At a

  • Spring Java Config. Use of PropertiesFactoryBean in the configuration file 2016-02-11

    I've the following configuration file @Configuration @ComponentScan(basePackages = "com.foo") @EnableTransactionManagement public class AppSpringConfiguration { @Autowired private Environment env; @Autowired private ApplicationContext appContext

  • In Socket.IO, should I use JSON for communication between server and client? 2012-05-03

    I'm building an MMO with Socket.IO and Node.js. It works quite fast (though I don't have 1000 players yet) but my feeling is that it's not very optimized. JSON is super cool and easy to use within Socket.IO but when I see a broadcast from the server

  • using wildcards for paths in sudoers file 2012-04-25

    I'm trying to set up the sudoers file to allow users to chown files only under a certain directory for example %hmis ALL=/bin/chown eng:hmis /usr/lib/bogimac/bsc/* is not good because hackers can do the following: sudo chown eng:hmis /usr/lib/bogimac

  • How to make a non-root user to use chown for any user group files? 2012-12-05

    I would like to make a user super powerful, with almost all root rights but unable to touch a the root user (to change the password of the root). My goal is to user "B" to manage my web server. The problem is user B need to able to run the chown

  • (Vim) How to use TAB for indentation in all file types? 2014-07-13

    I'm using only TAB for indent, so I configure Vim for using only them: set autoindent set noexpandtab set tabstop=4 set shiftwidth=4 But some files (.py) still using spaces. I've search for it and found: filetype plugin indent on But this has not hel

  • Easy-to-use program for directly transfering big files to an IP-address 2012-05-17

    I saw this xkcd comic and was horrified that he is actually right: So, is there an EASY program to share files directly over IP? In the spirit of: open it it displays your current IP tell it to the one who wants to send you a file he types it into an

  • Can I use RADIUS for strongswan - psk configured? 2014-01-13

    I'm a beginner for the strongswan server. And I was looking through the configuration examples from the strongswan.org. It seems the strongswan server should be configured to use EAP authentication to use RADIUS. Can anybody confirm this? Or please l

  • How to use timer for writing a new file with data everyday in Visual C++ 2016-01-29

    I have the source code of a VC++ 6.0 application that is used to communicate with a medical device and want it to modify such that the application creates a new file to dump data as the system date changes. I have no prior experience with Visual C++

  • first ipad Mini to use overseas for language translation: do I need SIM card? 2016-07-19

    Just ordered an Ipad mini for use overseas in various countries. We have purchased sim cards for our phones, but what do I need to make this ipad useful? I am also taking a camera. I will need to check my emails and post to social sites as well as le

  • RANCID, but for arbitrary server configuration files 2011-08-10

    Does anyone have advice on such a beast? I would prefer not to have to install additional software on my AIX machines, so etckeeper isn't ideal. It's also not centralized, based on my quick reading. Ideally, I would like something that runs under Lin

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development

search

Front-end development

Database

development tools

Open Platform

Javascript development

.NET development

cloud computing

server

Copyright (C) avrocks.com, All Rights Reserved.

processed in 2.573 (s). 13 q(s)