A JSON configuration utility for Perfect Swift

I’m getting myself further into Perfect Swift server…

A JSON configuration utility for Perfect Swift
Download JSONConfig from GitHub

In the previous post, my Acronym sample starter for getting SSL working on your server, in Environment.swift, I hard coded stuff like ports. Sure, some of the things would change depending on conditional compilation, but that’s not the best way to go.

Better is an external file that contains configuration information.

iamjono has a great little utility that uses JSON. However, the JSON file is flat. I can’t organize the configuration information into groups. With JSON, more can be done than a flat file.

In the JSONConfig utility I posted on GitHub, you can set the source for your JSONConfig and then get values based on a key path.

For example, suppose your configuration JSON file looks like this:

{
    "server": {
        "name": "www.your-domain.com",
        "port": 80
    },
    "database": {
        "host":     "127.0.0.1",
        "username": "db_bob",
        "password": "bob_password",
        "database": "db_bob"
    }
}

In your project code, you an access values by key path.

let serverName = JSONConfig.shared.string(forKeyPath: server.name")

The default value for a String at a path is “”. You can specify something else. For example:

let serverName = JSONConfig.shared.string(forKeyPath: "server.name", otherwise: "sub.your-domain.com")

In the current release, I’m just providing convenience routines for string, integer, double, and bool. I’ll provide other data types soon. Regardless, you can get a value at a key path using:

let it = JSONConfig.shared.value(forKeyPath: "your.path.to.value") // Any?

As a last note, it is always good to validate your JSON. There are lots available online. 🙂