Using JSON for Language-independent Configuration Files

Share this article

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' : ''

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]));


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.

James EdwardsJames Edwards
View Author

James is a freelance web developer based in the UK, specialising in JavaScript application development and building accessible websites. With more than a decade's professional experience, he is a published author, a frequent blogger and speaker, and an outspoken advocate of standards-based development.

Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week