JavaScript
Article
By James Edwards

Using JSON for Language-independent Configuration Files

By James Edwards

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"
--ADVERTISEMENT--

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.

Recommended
Sponsors
The most important and interesting stories in tech. Straight to your inbox, daily. Get Versioning.
Login or Create Account to Comment
Login Create Account