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 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.

Free Guide:

How to Choose the Right Charting Library for Your Application

How do you make sure that the charting library you choose has everything you need? Sign up to receive this detailed guide from FusionCharts, which explores all the factors you need to consider before making the decision.

  • Anonymous

    I’d just use XML, its way simpler than having to mess with all this crap.

  • bob

    I’d just use XML, its way simpler than having to mess with all this crap.

  • Andy_Read

    This is a neat hack if you’re a Javascript-centric developer, but beyond that it’s conceptually quite misleading. It’s not a language-independent config file: it’s a JSON config file, which is clearly not language independent – it’s part of the Javascript language. Just because you can get another language like PHP to read and parse a JSON file, doesn’t stop it being Javascript. I could make PHP read a C++ header file, but that wouldn’t make it language-independent, either.

    XML is the obvious format designed for language independent use on the web, but good old .ini files are just as language independent – they just require an equal amount of work to read, regardless of which language.

  • brothercake

    But why use a format that *every* language has to parse, when you can use a format that some languages understand natively?

    btw – JSON may have originally been a subset of javascript (or python, depending on your point of view), but it’s fast on its way to being an independent specification, with its own RFC and mime-type —

  • nickg

    nice idea.

    though did notice


    const is a Mozilla-specific extension, it is not supported by IE, but has been supported by Opera since version 9.0.

    so perhaps

    var config = {
    "lang" : "en",
    "host" : ""

    and your regex does not strip /* block style comments */


  • BartVG

    How about those good old INI-files? Apart from being a Windows invention (not entirely sure of this, though), their format is also well known and easy to read/parse.

    It’s true that Javascript can’t handle them as elegantly as JSON objects, but on the server side, there’s as much parsing needed for JSON objects as there is with INI files. (note: if this last sentence (the part after the last comma) is like a puzzle to you, it’s because I have a slight feeling that there’s something wrong with the word order. Or maybe not.)
    I mean, one would expect to be able to do something like json_decode(‘config.js’), which would give you a beautiful associated array immediately, instead of having to read the file, removing possible comments, extracting the part between curly braces and finally calling the current json_decode (which imo does just some extra parsing: you could easily split the contents into an array yourself).
    But you can of course always write your own json decoding function that does al this :-)
    (I would call it: jason_decode, pun intended)

  • BartVG

    But XML is obviously a better choice.

  • brothercake

    Nice pun :D On the flip side, wouldn’t if be funny to have a kid and call him Json :)

    But re: INI files – I wasn’t aware there was actually a proscribed format for that; I thought it was just a plain-text file extension convention ..?

  • El Guapo

    To anonymous aka bob,

    I disagree. XML is a lot heavier to deal with. Have you ever done parsing in Java for instance? That small amount of PHP is ridiculously simple in comparison.

    For many tasks, JSON is an excellent choice of format. Configuration files are one of them.

  • Anonymous

    I hate XML configuration files.

    However, the problem with JSON is that JSON doesn’t allow comments. It’s very useful to have comments in configuration files, which are usually meant to be read/edited by humans. Without native support for comments, you have to do hacky things like include comments as actual JSON objects, or use a preprocessor function that strips the JSON file of comments before parsing. Either way, the elegance and simplicity of the whole thing starts to become questionable.

Learn JavaScript for free!
Free course: Introduction to JavaScript

Yours when you take up a free 14-day SitePoint Premium trial.