JSON is everywhere. Most expect REST API responses as JSON. There are many libraries and frameworks that use JSON as a configuration file. In some cases, this is fine. In others, there may be more appropriate alternatives.
I do not intend to bash JSON; I only aim to point out that it should not be the default solution for configuration.
How did JSON become so popular as a configuration format?
I’m not sure. I would guess it has something to do with the popularity of Node.js and npm. npm uses a file named
package.json for configuring projects and packages. It might seem like I’m going to attack npm for using a JSON file, but I’m not.
In fact, there is a good reason that Node packages use JSON files. npm stores the information inside of package.json files in CouchDB. CouchDB is a database that makes JSON a first-class citizen. You can get a peek at how npm stores information by looking at the npm registry.
Let’s take a look at React. Notice the JSON document returned. Notice what’s in the “versions” object. It holds each published version of React. If you look at each version, notice that the information there resembles what is in a package.json file. When publishing a package, this is where information from the package.json goes.
The point here is that npm has a reason for using JSON configuration. There are some times where JSON is the right answer, and some times when it is not.
Why isn’t JSON a good format to use for configuration?
First, it doesn’t allow comments. You may want to explain your configuration or any configuration options. JSON doesn’t allow that. There are supersets of JSON that do, but those are no longer JSON.
Next, you may want to add dynamic content to your configuration. Or read from environment variables. JSON does not allow for any of these either. You could add a script to do so, but then you are adding something else on top of JSON. The above may be fine for your situation, but for others there may be better options.
What are good configuration file formats?
What is a good configuration format that isn’t language-specific? TOML. TOML is a great solution and my personal favorite. It allows comments, and has libraries in many programming languages. It is gaining popularity. Rust projects use TOML for package configuration. There are many other projects that use it too.
The next time you are in a position to create a configuration file, think through your options. From there, decide what is best for you, your team, and the project.